Archive for the ‘Policy Injection’ tag
How-to AOP: Validation with Unity
With the introduction of Unity v1.2 it is now possible to do aspect oriented programming (AOP) using Unity in a way that is similar to Policy Injection. You can read all about it in my former post How-to AOP: Validation with Policy Injection, where I showed how-to AOP using Validation with the Policy Injection Application Block (PIAB).
The example of today is a rework of the previous Policy Injection example, so most code remains unchanged. Most important exercise is that the invoking code in the method Save of the facade CustomerManager is changed so – surprise, surprise – Unity does the AOP work instead of Policy Injection.
Unfortunately, out-of-the-box Unity does not have something like an ArgumentValidationException.
So, some extra code has to be written, mostly to make Unity do its AOP thing work. To stay in line with the PIAB example, some behavior of the Policy Injection ValidationCallHandler is mimiced: when validation fails, an exception is thrown.
Of course, you can reuse the ArgumentValidationException of PIAB, but then you still need PIAB. For this example, I am an Unity purist and create something myself that looks like an ArgumentValidationException, smells like an ArgumentValidationException, in fact is called an…
… EntityValidationException.
Yeah right, I gave it a different name for educational purposes so you wouldn’t think: Wow, Unity also has this powerful way of handling validation. What a great piece of work this Unity is!
Well, maybe Policy Injection will fully integrated in the next version of Unity. Maybe not.
First, you have to change the code in the method Save of CustomerManager to use Unity:
public bool Save(Customer customer)
{
bool IsValid = false;
IUnityContainer container = new UnityContainer();
container.AddNewExtension();
container.RegisterType().Configure().SetInterceptorFor(new InterfaceInterceptor());
IRepository action = container.Resolve();
try
{
action.Save(customer);
}
catch (EntityValidationException ex)
{
ValidationResults results = ex.ValidationResults;
// ...
}
return IsValid;
}
Essentially, this is the most important part of the exercise. As you can see, Unity uses an interception mechanism for the AOP behavior. As in the Policy Injection example, an interface is needed for registering the type. Unity has no built-in ValidationCallHandler like Policy Injection, so you have to create one yourself. This is not very difficult, see below:
public interface IRepository
{
[EntityValidation]
void Save(Customer customer);
}
EntityValidation is a concrete HandlerAttribute:
public class EntityValidationAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new EntityValidationHandler();
}
}
A HandlerAttribute needs to return a concrete class which implements ICallHandler:
public class EntityValidationHandler : ICallHandler
{
public int Order { get; set; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
Customer customer = input.Arguments[0] as Customer;
ValidationResults results = Validation.Validate(customer);
if (results.Count == 0)
{
return getNext()(input, getNext);
}
else
{
throw new EntityValidationException(results);
}
}
}
Lastly, you need an exception to mimic the ArgumentValidationException:
[Serializable]
public class EntityValidationException : Exception, ISerializable
{
readonly private ValidationResults validationResults;
public EntityValidationException(ValidationResults validationResults)
{
this.validationResults = validationResults;
}
protected EntityValidationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.validationResults = (ValidationResults)info.GetValue("EntityValidationException.validationResults", typeof(ValidationResults));
}
public ValidationResults ValidationResults
{
get { return validationResults; }
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("EntityValidationException.validationResults", validationResults);
}
}
That’s most of it. Nice, huh? To be honest with you: I slightly prefer Policy Injection over Unity Interception. Why? It feels like the subtle difference Policy Injection is AOP and Unity supports AOP. It’s just a feeling.
How-to AOP: Validation with Policy Injection
Validation of user input is very important. A lot of our users are very environmentally aware and throw all kinds of garbage in (= garbage out). So you probably better use extensive validation for all your dataclasses (or Business Entities, if you like). A consequence is that you have to invoke validation almost everywhere in your business logic. That’s a lot of boooooring repetitive work.
To me this smells like a cross-cutting ‘AOP’ concern, i.e. use Policy Injection.
In the following example of validation “the AOP way” I show you how to use Validation with Policy Injection, which are both part of Enterprise Library.
For simplicity we are going to validate a very simple Customer class, which still is very realistic. Even in the real world you can come across some really simple customers, like this one:
“I do not want to pay a penny extra for validation. When I buy me an application I expect that you deliver one fully validated without errors in it. So if you want validation, please do it at your own expense.”
Yes, this customer is in heavily need of managing customer expectation, but that’s a different story.
The how-to example is build around a Factory Design pattern (Customer, interface IRepository, and concrete class CustomerRepository) and accessed via Facade pattern (CustomerManager). I use a facade here, because then you do not not have to reference parts of Enterprise Library in your client code. Enterprise Library can stay within a single class library together with the other stuff. Isolation of the chosen technical implementation. In this way we can easily replace it with a better implementation, if we don’t like Policy Injection any more.
public class Customer
{
string m_FullName;
[StringLengthValidator(5)]
public string FullName
{
get { return m_FullName; }
set { m_FullName = value; }
}
}
The property FullName is decorated with a validation attribute StringLengthValidator. Upon validation it is checked if the length of the string does not exceed 5. I know, silly validation.
The client code is as follows, it just calls the CustomerManager facade:
CustomerManager mgr = new CustomerManager(); Customer customer = new Customer(); customer.FullName = "thisisaverylongname"; bool IsValid = mgr.Save(customer);
The CustomerManager façade:
public bool Save(Customer customer)
{
bool IsValid = false;
IRepository ctr = PolicyInjection.Create();
try
{
ctr.Save(customer);
IsValid = true;
}
catch (ArgumentValidationException ex)
{
ValidationResults results = ex.ValidationResults;
// ...
}
return IsValid;
}
Finally, the interface IRepository and its concrete class CustomerRepository:
//IRepository interface:
interface IRepository
{
[ValidationCallHandler]
void Save(Customer customer);
}
class CustomerRepository : IRepository
{
void IRepository.Save(Customer customer)
{
// Saving logic...
}
}
With this concrete example at hand you should have a start of and be able to experiment a little bit with validation the AOP way.
If you need some extra help with the above example or have a strong opinion towards use of the Policy Injection, just leave a comment.















