-
Notifications
You must be signed in to change notification settings - Fork 3
Policy injection
Isaac Abraham edited this page Jan 26, 2016
·
24 revisions
Policy Injection is a powerful mechanism in Unity to perform decoration and composition style patterns, encouraging separation of concerns and reusability. However, it can be somewhat difficult to implement. There are normally several steps to enable policy injection in Unity: -
- Ensure that the
InterceptionExtension
has been loaded into Unity. - Create a call handler that implements the
ICallHandler
interface. - Create a policy that applies the call handler under certain circumstances, or derive from the built-in Unity
HandlerAttribute
which will automatically create a policy for you. - Ensure that you register any types that you want to partake in Policy Injection with two
InjectionMembers
: -InjectionBehaviour<PolicyInjectionBehaviour>
Interceptor<InterfaceInterceptor>
The Automapper simplifies this in three ways: -
- It automatically turns on the
InterceptionExtension
if required. - If you apply any attributes that derives from
HandlerAttribute
on a type, it will automatically turn on Policy Injection for that type. You do not have to explicitly mark the type in any way for policy injection.
// An attribute that derives from HandlerAttribute.
[ArgumentNotNull]
interface IMyService { }
class MyService : IMyService { }
container.AutomapAssemblies("MyAssembly");
// IMyService is now registered to MyService using the PolicyInjectionBehavior and InterfaceInterceptor.
// MyService will now get the ArgumentNotNullHandler applied to all IMyService methods.
- If you are using call handlers through another mechanism than through HandlerAttributes e.g. creating policies manually on the Container to act upon many classes simultaneously, then marking the interface that you wish to participate in Policy Injection as follows will automatically carry out step 4 above e.g.
// First we create a policy to turn apply the ArgumentNotNullHandler to all public methods on all types that are registered for policy injection.
container.Configure<Interception>()
.AddPolicy("NullArgumentChecking")
.AddCallHandler<ArgumentNotNullHandler>()
.AddMatchingRule(new MemberNameMatchingRule("*"));
// Attribute-based approach to register IMyService for policy injection
[PolicyInjection]
interface IMyService { }
class MyService : IMyService { }
// Fluent alternative
AutomapperConfig.Create()
.AndUsePolicyInjectionFor(typeof(IMyService));
container.AutomapAssemblies("MyAssembly");
// Interception Extension has now been enabled.
// IMyService is now registered to MyService using the PolicyInjectionBehavior and InterfaceInterceptor.
// MyService will now get the ArgumentNotNullHandler applied to all IMyService methods.