Contents tagged with Unity

  • Unity – Part 6: Registration by Convention

    Introduction

    OK, sixth post on this series, long overdue. You will find the fifth (Injecting Values) here, the fourth (Extensions) here, the third (Aspect-Oriented Programming) here, the second (Dependency Injection) here and the first one (Introduction) here.

    This time I’m going to talk about something that came out in Unity 3, automatic (or convention-based) registration of components.

    Automatic Registration

    Normally, you register your components by using one of the Register* methods declared in IUnityContainer. The problem is that this has to be done explicitly for each component. Well, since Unity 3, we now have an automatic, convention-based mechanism.

    The automatic configuration has two options:

    1. Using the RegisterTypes method overload that takes several parameters: one for each type to map, a delegate for choosing the registration keys, a delegate for choosing the name of the registration and finally another one for selecting the lifetime manager;
    2. Using the RegisterTypes overload that takes a single instance of a RegistrationConvention-derived class.

    So, here’s an example of the first approach:

       1: unity.RegisterTypes(AllClasses.FromAssemblies(new Assembly[] { Assembly.GetExecutingAssembly() }), WithMappings.FromAllInterfacesInSameAssembly, WithName.TypeName, WithLifetime.ContainerControlled);

    This will map all of the types that implement interfaces in the current assembly from their interfaces, provided they belong to the same assembly of their implementation, with a name equal to the implementation type and with a lifetime of singleton.

    A more sensible approach, however, might be instead:

       1: unity.RegisterTypes(AllClasses.FromAssemblies(new Assembly[] { Assembly.GetExecutingAssembly() }).Where(x => (x.IsPublic == true) && (x.GetInterfaces().Any() == true) && (x.IsAbstract == false) && (x.IsClass == true)), WithMappings.FromAllInterfacesInSameAssembly, type => (unity.Registrations.Select(x => x.RegisteredType).Any(r => type.GetInterfaces().Contains(r) == true) == true) ? WithName.TypeName(type) : WithName.Default(type), WithLifetime.ContainerControlled);

    This has the following advantage: maps the first found implementation with an empty name, and the others with a name equal to the implementation type.

    A RegistrationConvention class could be like this:

       1: public class InterfaceToTypeConvention : RegistrationConvention
       2: {
       3:     private readonly IUnityContainer unity;
       4:     private readonly IEnumerable<Type> types;
       5:  
       6:     public InterfaceToTypeConvention(IUnityContainer unity, params Assembly [] assemblies) : this(unity, assemblies.SelectMany(a => a.GetExportedTypes()).ToArray())
       7:     {
       8:         this.unity = unity;
       9:     }
      10:  
      11:     public InterfaceToTypeConvention(IUnityContainer unity, params Type[] types)
      12:     {
      13:         this.unity = unity;
      14:         this.types = types ?? Enumerable.Empty<Type>();
      15:     }
      16:  
      17:     public override Func<Type, IEnumerable<Type>> GetFromTypes()
      18:     {
      19:         return (WithMappings.FromAllInterfacesInSameAssembly);
      20:     }
      21:  
      22:     public override Func<Type, IEnumerable<InjectionMember>> GetInjectionMembers()
      23:     {
      24:         return (x => Enumerable.Empty<InjectionMember>());
      25:     }
      26:  
      27:     public override Func<Type, LifetimeManager> GetLifetimeManager()
      28:     {
      29:         return (WithLifetime.ContainerControlled);
      30:     }
      31:  
      32:     public override Func<Type, String> GetName()
      33:     {
      34:         return (type => (this.unity.Registrations.Select(x => x.RegisteredType).Any(r => type.GetInterfaces().Contains(r) == true) == true) ? WithName.TypeName(type) : WithName.Default(type));
      35:     }
      36:  
      37:     public override IEnumerable<Type> GetTypes()
      38:     {
      39:         return (this.types.Where(x => (x.IsPublic == true) && (x.GetInterfaces().Any() == true) && (x.IsAbstract == false) && (x.IsClass == true)));
      40:     }
      41: }

    And its registration:

       1: unity.RegisterTypes(new InterfaceToTypeConvention(unity, Assembly.GetExecutingAssembly()));

    Obviously, this approach is more reusable, the same convention class can be carried over to different projects.

    One thing worth mentioning: if you specify a lifetime manager, anyone other than null, each registered type will be mapped to itself, besides to its interfaces. For example, a class MyService that implements IMyService will be mapped both as IMyService –> MyService and MyService –> MyService. This is by design.

    Conclusion

    And that’s it for automatic configurations. Now it’s up to you to customize how you want things to be registered: name of the registration, lifetime, etc.

    Stay tuned for more on Unity soon!

    Read more...

  • Unity – Part 5: Injecting Values

    Introduction

    This is the fifth post on Unity. You can find the introductory post here, the second post, on dependency injection here, a third one on Aspect Oriented Programming (AOP) here and the latest so far, on writing custom extensions, here. This time we will talk about injecting simple values.

    An Inversion of Control (IoC) / Dependency Injector (DI) container like Unity can be used for things other than injecting complex class dependencies. It can also be used for setting property values or method/constructor parameters whenever a class is built. The main difference is that these values do not have a lifetime manager associated with them and do not come from the regular IoC registration store. Unlike, for instance, MEF, Unity won’t let you register as a dependency a string or an integer, so you have to take a different approach, which I will describe in this post.

    Scenario

    Let’s imagine we have a base interface that describes a logger – the same as in previous examples:

       1: public interface ILogger
       2: {
       3:     void Log(String message);
       4: }

    And a concrete implementation that writes to a file:

       1: public class FileLogger : ILogger
       2: {
       3:     public String Filename
       4:     {
       5:         get;
       6:         set;
       7:     }
       8:  
       9:     #region ILogger Members
      10:  
      11:     public void Log(String message)
      12:     {
      13:         using (Stream file = File.OpenWrite(this.Filename))
      14:         {
      15:             Byte[] data = Encoding.Default.GetBytes(message);
      16:             
      17:             file.Write(data, 0, data.Length);
      18:         }
      19:     }
      20:  
      21:     #endregion
      22: }

    And let’s say we want the Filename property to come from the application settings (appSettings) section on the Web/App.config file.

    As usual with Unity, there is an extensibility point that allows us to automatically do this, both with code configuration or statically on the configuration file.

    Extending Injection

    We start by implementing a class that will retrieve a value from the appSettings by inheriting from ValueElement:

       1: sealed class AppSettingsParameterValueElement : ValueElement, IDependencyResolverPolicy
       2: {
       3:     #region Private methods
       4:     private Object CreateInstance(Type parameterType)
       5:     {
       6:         Object configurationValue = ConfigurationManager.AppSettings[this.AppSettingsKey];
       7:  
       8:         if (parameterType != typeof(String))
       9:         {
      10:             TypeConverter typeConverter = this.GetTypeConverter(parameterType);
      11:  
      12:             configurationValue = typeConverter.ConvertFromInvariantString(configurationValue as String);
      13:         }
      14:  
      15:         return (configurationValue);
      16:     }
      17:     #endregion
      18:  
      19:     #region Private methods
      20:     private TypeConverter GetTypeConverter(Type parameterType)
      21:     {
      22:         if (String.IsNullOrEmpty(this.TypeConverterTypeName) == false)
      23:         {
      24:             return (Activator.CreateInstance(TypeResolver.ResolveType(this.TypeConverterTypeName)) as TypeConverter);
      25:         }
      26:         else
      27:         {
      28:             return (TypeDescriptor.GetConverter(parameterType));
      29:         }
      30:     }
      31:     #endregion
      32:  
      33:     #region Public override methods
      34:     public override InjectionParameterValue GetInjectionParameterValue(IUnityContainer container, Type parameterType)
      35:     {
      36:         Object value = this.CreateInstance(parameterType);
      37:         return (new InjectionParameter(parameterType, value));
      38:     }
      39:     #endregion
      40:  
      41:     #region IDependencyResolverPolicy Members
      42:  
      43:     public Object Resolve(IBuilderContext context)
      44:     {
      45:         Type parameterType = null;
      46:  
      47:         if (context.CurrentOperation is ResolvingPropertyValueOperation)
      48:         {
      49:             ResolvingPropertyValueOperation op = (context.CurrentOperation as ResolvingPropertyValueOperation);
      50:             PropertyInfo prop = op.TypeBeingConstructed.GetProperty(op.PropertyName);
      51:             parameterType = prop.PropertyType;
      52:         }
      53:         else if (context.CurrentOperation is ConstructorArgumentResolveOperation)
      54:         {
      55:             ConstructorArgumentResolveOperation op = (context.CurrentOperation as ConstructorArgumentResolveOperation);
      56:             String args = op.ConstructorSignature.Split('(')[1].Split(')')[0];
      57:             Type[] types = args.Split(',').Select(a => Type.GetType(a.Split(' ')[0])).ToArray();
      58:             ConstructorInfo ctor = op.TypeBeingConstructed.GetConstructor(types);
      59:             parameterType = ctor.GetParameters().Where(p => p.Name == op.ParameterName).Single().ParameterType;
      60:         }
      61:         else if (context.CurrentOperation is MethodArgumentResolveOperation)
      62:         {
      63:             MethodArgumentResolveOperation op = (context.CurrentOperation as MethodArgumentResolveOperation);
      64:             String methodName = op.MethodSignature.Split('(')[0].Split(' ')[1];
      65:             String args = op.MethodSignature.Split('(')[1].Split(')')[0];
      66:             Type[] types = args.Split(',').Select(a => Type.GetType(a.Split(' ')[0])).ToArray();
      67:             MethodInfo method = op.TypeBeingConstructed.GetMethod(methodName, types);
      68:             parameterType = method.GetParameters().Where(p => p.Name == op.ParameterName).Single().ParameterType;
      69:         }
      70:  
      71:         return (this.CreateInstance(parameterType));
      72:     }
      73:  
      74:     #endregion
      75:  
      76:     #region Public properties
      77:     [ConfigurationProperty("appSettingsKey", IsRequired = true)]
      78:     public String AppSettingsKey
      79:     {
      80:         get
      81:         {
      82:             return ((String)base["appSettingsKey"]);
      83:         }
      84:  
      85:         set
      86:         {
      87:             base["appSettingsKey"] = value;
      88:         }
      89:     }
      90:     #endregion
      91: }  

    As you can see from the implementation of the IDependencyResolverPolicy.Resolve method, this will work in three different scenarios:

    • When it is applied to a property;
    • When it is applied to a constructor parameter;
    • When it is applied to an initialization method.

    The implementation will even try to convert the value to its declared destination, for example, if the destination property is an Int32, it will try to convert the appSettings stored string to an Int32.

    Injection By Configuration

    If we want to configure injection by configuration, we need to implement a custom section extension by inheriting from SectionExtension, and registering our custom element with the name “appSettings”:

       1: sealed class AppSettingsParameterInjectionElementExtension : SectionExtension
       2: {
       3:     public override void AddExtensions(SectionExtensionContext context)
       4:     {
       5:         context.AddElement<AppSettingsParameterValueElement>("appSettings");
       6:     }
       7: }

    And on the configuration file, for setting a property, we use it like this:

       1: <appSettings>
       2:     <add key="LoggerFilename" value="Log.txt"/>
       3: </appSettings>
       4: <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
       5:     <container>
       6:         <register type="MyNamespace.ILogger, MyAssembly" mapTo="MyNamespace.ConsoleLogger, MyAssembly"/>
       7:         <register type="MyNamespace.ILogger, MyAssembly" mapTo="MyNamespace.FileLogger, MyAssembly" name="File">
       8:             <lifetime type="singleton"/>
       9:             <property name="Filename">
      10:                 <appSettings appSettingsKey="LoggerFilename"/>
      11:             </property>
      12:         </register>
      13:     </container>
      14: </unity>

    If we would like to inject the value as a constructor parameter, it would be instead:

       1: <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
       2:     <sectionExtension type="MyNamespace.AppSettingsParameterInjectionElementExtension, MyAssembly" />
       3:     <container>
       4:         <register type="MyNamespace.ILogger, MyAssembly" mapTo="MyNamespace.ConsoleLogger, MyAssembly"/>
       5:         <register type="MyNamespace.ILogger, MyAssembly" mapTo="MyNamespace.FileLogger, MyAssembly" name="File">
       6:             <lifetime type="singleton"/>
       7:             <constructor>
       8:                 <param name="filename" type="System.String">
       9:                     <appSettings appSettingsKey="LoggerFilename"/>
      10:                 </param>
      11:             </constructor>
      12:         </register>
      13:     </container>
      14: </unity>

    Notice the appSettings section, where we add a LoggerFilename entry, which is the same as the one referred by our AppSettingsParameterInjectionElementExtension extension.

    For more advanced behavior, you can add a TypeConverterName attribute to the appSettings declaration, where you can pass an assembly qualified name of a class that inherits from TypeConverter. This class will be responsible for converting the appSettings value to a destination type.

    Injection By Attribute

    If we would like to use attributes instead, we need to create a custom attribute by inheriting from DependencyResolutionAttribute:

       1: [Serializable]
       2: [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
       3: public sealed class AppSettingsDependencyResolutionAttribute : DependencyResolutionAttribute
       4: {
       5:     public AppSettingsDependencyResolutionAttribute(String appSettingsKey)
       6:     {
       7:         this.AppSettingsKey = appSettingsKey;
       8:     }
       9:  
      10:     public String TypeConverterTypeName
      11:     {
      12:         get;
      13:         set;
      14:     }
      15:  
      16:     public String AppSettingsKey
      17:     {
      18:         get;
      19:         private set;
      20:     }
      21:  
      22:     public override IDependencyResolverPolicy CreateResolver(Type typeToResolve)
      23:     {
      24:         return (new AppSettingsParameterValueElement() { AppSettingsKey = this.AppSettingsKey, TypeConverterTypeName = this.TypeConverterTypeName });
      25:     }
      26: }

    As for file configuration, there is a mandatory property for setting the appSettings key and an optional TypeConverterName  for setting the name of a TypeConverter.

    Both the custom attribute and the custom section return an instance of the injector AppSettingsParameterValueElement that we implemented in the first place. Now, the attribute needs to be placed before the injected class’ Filename property:

       1: public class FileLogger : ILogger
       2: {
       3:     [AppSettingsDependencyResolution("LoggerFilename")]
       4:     public String Filename
       5:     {
       6:         get;
       7:         set;
       8:     }
       9:  
      10:     #region ILogger Members
      11:  
      12:     public void Log(String message)
      13:     {
      14:         using (Stream file = File.OpenWrite(this.Filename))
      15:         {
      16:             Byte[] data = Encoding.Default.GetBytes(message);
      17:             
      18:             file.Write(data, 0, data.Length);
      19:         }
      20:     }
      21:  
      22:     #endregion
      23: }

    Or, if we wanted to use constructor injection:

       1: public class FileLogger : ILogger
       2: {
       3:     public String Filename
       4:     {
       5:         get;
       6:         set;
       7:     }
       8:  
       9:     public FileLogger([AppSettingsDependencyResolution("LoggerFilename")] String filename)
      10:     {
      11:         this.Filename = filename;
      12:     }
      13:  
      14:     #region ILogger Members
      15:  
      16:     public void Log(String message)
      17:     {
      18:         using (Stream file = File.OpenWrite(this.Filename))
      19:         {
      20:             Byte[] data = Encoding.Default.GetBytes(message);
      21:             
      22:             file.Write(data, 0, data.Length);
      23:         }
      24:     }
      25:  
      26:     #endregion
      27: }

    Usage

    Just do:

       1: ILogger logger = ServiceLocator.Current.GetInstance<ILogger>("File");

    And off you go! A simple way do avoid hardcoded values in component registrations. Of course, this same concept can be applied to registry keys, environment values, XML attributes, etc, etc, just change the implementation of the AppSettingsParameterValueElement class.

    Next stop: custom lifetime managers.

    Read more...

  • Unity – Part 4: Extensions

    Extensions

    Another long overdue post on Unity. See the first here for an introduction, the second here for dependency injection and the third here for AOP with Unity.

    Unity allows adding extensions to it. An extension is something that enhances its functionality somehow, or that configures some aspect of it so that you don’t have to do it manually. In Unity, an extension is a class that inherits from the abstract base class UnityContainerExtension. It can have multiple extensions, which are processed by the order on which they are declared – more on this later. The collection of actually loaded extensions is hidden inside of Unity, the only operations you can perform are add or remove an extension.

    You already know from post three that if you want to use AOP – or Interception, in Unity terms – you must add the Interception extension. You also saw that we must tell Unity which of the interception strategies it must use for each registration upon which you want to apply aspects – VirtualMethodInterceptor, TransparentProxyInterceptor or InterfaceInterceptor. This is rather boring, so why not turn this into an extension that does all the work? The following code does just that:

       1: public class DefaultInterception : Interception
       2: {
       3:     #region Private static readonly fields
       4:     private static readonly IInterceptor [] interceptors = typeof(IInterceptor)
       5:         .Assembly
       6:         .GetExportedTypes()
       7:         .Where(type => 
       8:             (typeof(IInterceptor).IsAssignableFrom(type) == true) &&
       9:             (type.IsAbstract == false) &&
      10:             (type.IsInterface == false))
      11:         .Select(type => Activator.CreateInstance(type) as IInterceptor)
      12:         .ToArray();
      13:     #endregion
      14:  
      15:     #region Protected override methods
      16:     protected override void Initialize()
      17:     {
      18:         base.Initialize();
      19:  
      20:         IConfigurationSource configSource = ConfigurationSourceFactory.Create();
      21:         PolicyInjectionSettings section = configSource.GetSection(PolicyInjectionSettings.SectionName) as PolicyInjectionSettings;
      22:  
      23:         if (section != null)
      24:         {
      25:             section.ConfigureContainer(this.Container, configSource);
      26:         }
      27:  
      28:         this.Context.Registering += delegate(Object sender, RegisterEventArgs e)
      29:         {                
      30:             this.setInterceptorFor(e.TypeFrom, e.TypeTo, e.Name, e.LifetimeManager);
      31:         };
      32:  
      33:         this.Context.RegisteringInstance += delegate(Object sender, RegisterInstanceEventArgs e)
      34:         {
      35:             this.setInstanceInterceptorFor(e.RegisteredType, e.Name, e.Instance, e.LifetimeManager);
      36:         };
      37:     }
      38:     #endregion
      39:  
      40:     #region Private methods
      41:     private void setInterceptorFor(Type typeFrom, Type typeTo, String name, LifetimeManager lifetimeManager)
      42:     {
      43:         foreach (IInterceptor interceptor in interceptors)
      44:         {
      45:             if ((interceptor.CanIntercept(typeFrom) == true) && (interceptor.GetInterceptableMethods(typeFrom, typeTo).Count() != 0))
      46:             {
      47:                 if (interceptor is IInstanceInterceptor)
      48:                 {                        
      49:                     this.Container.Configure<Interception>().SetInterceptorFor(typeFrom, name, interceptor as IInstanceInterceptor);
      50:                 }
      51:                 else if (interceptor is ITypeInterceptor)
      52:                 {
      53:                     this.Container.Configure<Interception>().SetInterceptorFor(typeFrom, name, interceptor as ITypeInterceptor);
      54:                 }
      55:  
      56:                 //add a custom behavior for all types
      57:  
      58:                 break;
      59:             }
      60:         }
      61:     }
      62:  
      63:     private void setInstanceInterceptorFor(Type registeredType, String name, Object instance, LifetimeManager manager)
      64:     {
      65:         foreach (IInstanceInterceptor interceptor in interceptors.OfType<IInstanceInterceptor>())
      66:         {
      67:             if ((interceptor.CanIntercept(registeredType) == true) && (interceptor.GetInterceptableMethods(registeredType, instance.GetType()).Count() != 0))
      68:             {
      69:                 this.Container.Configure<Interception>().SetInterceptorFor(registeredType, name, interceptor);
      70:                 break;
      71:             }
      72:         }
      73:     }
      74:     #endregion
      75: }

    As you can see, I inherited from Interception, which provides the AOP functionality, so I don't have to add it too. On the Initialize method we have access to both the Container (IUnityContainer) as well as a Context (ExtensionObject), which we can access freely. In this case, I hooked up to its Registering and RegisteringInstance events and, whenever a registration is made, I set up an appropriate interceptor, which I got from the list of default interceptor (IInterceptor) implementations.

    Registration By Code

    So, you need to register this extension, which you can do by code, by using the AddExtension or AddNewExtension<T> methods:

       1: IUnityContainer unity = ...;
       2:  
       3: unity.AddNewExtension<DefaultInterception>();

    Beware, you must do this before actually registering something, because if you do it later, the events won’t get fired.

    Registration By Configuration

    If you place the registration on the .config file, you do no have to be concerned about doing it before the registrations:

       1: <configuration>
       2:     <configSections>
       3:         <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
       4:     </configSections>
       5:     <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
       6:         <container>
       7:             <extension type="MyNamespace.DefaultInterception, MyAssembly"/>
       8:         </container>
       9:     </unity>
      10: </configuration>

    Configuring

    In both cases, if the extension needs configuring, you can access it by using the Configure method:

       1: DefaultInterception extension = unity.Configure<DefaultInterception>();

    This will only return the already registered extension, not create a new one.

    Other Uses

    Other common uses might include, for example, setting up the Common Service Locator, or setting up some interception behavior.

    Next in line: injecting values into registrations. Stay tuned!

    Read more...

  • Unity – Part 3: Aspect Oriented Programming

    AOP

    This is my third post on Unity. See the first here for an introduction and the second here for how to apply dependency injection.

    Aspect Oriented Programming (AOP) is a technique for applying cross-cutting concerns to existing implementations, without modifying them. Some examples of it are:

    • Wrapping method calls that go to the database in transactions automatically;
    • Logging all calls to some method, including the input parameters and return value;
    • Catching exceptions thrown in a method automatically and doing something with them.

    AOP is supported in the Enterprise Library (of which Unity is part) by the Policy Injection application block, and it can be integrated with Unity. You must install this application block, perhaps by using NuGet:

    image

    We need to add the interception behavior – which is the one that actually applies aspects – to Unity, either by code:

       1: unity.AddNewExtension<Interception>();

    Or by XML configuration:

       1: <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
       2:     <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration"/>
       3: </unity>

    Having said that, the first concept we need to know is that of an interceptor. An interceptor in the Policy Injection block is an implementation of Microsoft.Practices.Unity.InterceptionExtension.IInterceptor interface, and there are three implementations:

    It is required that, when you are going to apply an aspect to a registration, you choose an interceptor suitable for that registration, based on what type we are registering.

    An aspect itself is an implementation of Microsoft.Practices.Unity.InterceptionExtension.ICallHandler, Unity includes five out of the box such handlers:

    The ICallHandler interface only defines a single method, Invoke, which wraps a method’s arguments and allows having code run before, after or even instead of the target method, and an Order property, for specifying the order by which the aspect should be applied, in case there are many.

    A simple call handler, for outputting some string before or after a method call, might be:

       1: public class OutputCallHandler : ICallHandler
       2: {
       3:     public Boolean Before
       4:     {
       5:         get;
       6:         set;
       7:     }
       8:  
       9:     public Boolean After
      10:     {
      11:         get;
      12:         set;
      13:     }
      14:  
      15:     public String Message
      16:     {
      17:         get;
      18:         set;
      19:     }
      20:  
      21:     Int32 ICallHandler.Order
      22:     {
      23:         get;
      24:         set;
      25:     }
      26:  
      27:     IMethodReturn ICallHandler.Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
      28:     {
      29:         if (this.Before == true)
      30:         {
      31:             Console.WriteLine(this.Message);
      32:         }
      33:  
      34:         IMethodReturn result = getNext()(input, getNext);
      35:  
      36:         if (result.Exception != null)
      37:         {
      38:             Console.Error.WriteLine(result.Exception.Message);
      39:         }
      40:         else
      41:         {
      42:             if (this.After == true)
      43:             {
      44:                 Console.WriteLine(this.Message);
      45:             }
      46:         }
      47:  
      48:         return (result);
      49:     }
      50: }

    Another option is to have interception for all methods of the target registration, which can be achieved by implementing Microsoft.Practices.Unity.InterceptionExtension.IInterceptionBehavior in a concrete class, such as this:

       1: public class MyInterceptionBehavior : IInterceptionBehavior
       2: {
       3:     IEnumerable<Type> IInterceptionBehavior.GetRequiredInterfaces()
       4:     {
       5:         return (Type.EmptyTypes);
       6:     }
       7:  
       8:     IMethodReturn IInterceptionBehavior.Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
       9:     {
      10:         //before target method call
      11:  
      12:         if (input.MethodBase == typeof(MyService).GetMethod("DoSomething"))
      13:         {
      14:             //do something
      15:         }
      16:  
      17:         IMethodReturn methodReturn = getNext().Invoke(input, getNext);
      18:  
      19:         //after target method call
      20:  
      21:         return (methodReturn);
      22:     }
      23:  
      24:     Boolean IInterceptionBehavior.WillExecute
      25:     {
      26:         get
      27:         {
      28:             return (true);
      29:         }
      30:     }
      31: }

    If we want to cancel the default method call, if it is non void, we must return an appropriate value:

       1: IMethodReturn methodReturn = input.CreateMethodReturn(someValue, input.Arguments);

    Or if we want to return an exception:

       1: IMethodReturn methodReturn = input.CreateExceptionMethodReturn(new SomeException());

    There are three ways by which we can apply an aspect to a registration:

    • By applying an attribute to a method on the declaring or target type;
    • By code configuration;
    • By XML configuration.

    Interception By Attributes

    We need to create an attribute that derives from Microsoft.Practices.Unity.InterceptionExtension.HandlerAttribute and which instantiates our call handler:

       1: [Serializable]
       2: [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
       3: public sealed class OutputCallHandlerAttribute : HandlerAttribute
       4: {
       5:     public Boolean Before
       6:     {
       7:         get;
       8:         set;
       9:     }
      10:  
      11:     public Boolean After
      12:     {
      13:         get;
      14:         set;
      15:     }
      16:  
      17:     public String Message
      18:     {
      19:         get;
      20:         private set;
      21:     }
      22:  
      23:     public OutputCallHandlerAttribute(String message)
      24:     {
      25:         this.Message = message;
      26:     }
      27:  
      28:     public override ICallHandler CreateHandler(IUnityContainer container)
      29:     {
      30:         return (new OutputCallHandler() { After = this.After, Before = this.Before, Message = this.Message });
      31:     }        
      32: }

    And we apply it to any method declaration:

       1: public interface IMyService
       2: {
       3:     [OutputCallHandler("Before", Before = true)]
       4:     [OutputCallHandler("After", After = true)]
       5:     void DoSomething();
       6: }

    But before this works, we need to tell Unity to use interface interception for our type:

       1: unity.Configure<Interception>().SetDefaultInterceptorFor<IMyService>(new InterfaceInterceptor());

    Interception By Code

    For intercepting by code, whenever we register something with Unity, we also tell it to use interface interception and to include a behavior instance – it is not possible to specify a call handler for a specific method:

       1: unity.RegisterType<IMyService, MyService>(new ContainerControlledLifetimeManager(), new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<OutputInterceptionBehavior>());

    Interception By Configuration

    When applying interception by configuration we also cannot target a specific method, but instead specify an interception behavior, which will apply to all method – of course, inside of it we can do our own filtering, by looking at the IMethodInvocation.MethodBase property:

       1: <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
       2:     <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration"/>
       3:     <container>
       4:         <extension type="Microsoft.Practices.Unity.InterceptionExtension.Interception, Microsoft.Practices.Unity.Interception"/>
       5:         <interceptors>
       6:             <interceptor type="InterfaceInterceptor">
       7:                 <default type="MyNamespace.IMyService, MyAssembly"/>
       8:             </interceptor>
       9:         </interceptors>
      10:         <register type="MyNamespace.IMyService, MyAssembly" mapTo="MyNamespace.MyService, MyAssembly">
      11:             <lifetime type="singleton"/>
      12:             <interceptionBehavior type="MyNamespace.OutputInterceptionBehavior, MyAssembly"/>
      13:         </register>
      14:         </register>
      15:     </container>
      16: </unity>

    Executing

    You must Unity to retrieve an instance, which will be properly wrapped in a proxy, and from there all of your configured interceptors will be called:

       1: IMyService svc = ServiceLocator.Current.GetInstance<IMyService>();
       2: svc.DoSomething();

    Next in line: extending Unity.

    Read more...

  • Unity – Part 2: Dependency Injection

    Dependency Injection

    Second part of my series on Unity. For an introduction, read the first post.

    OK, now we know how to get Inversion of Control (IoC): instead of referencing a particular concrete implementation, we instead reference an interface or an abstract base class, which creates a level of abstraction and allows us to change things at a later time.

    Now let’s see what Unity has to offer in terms of Dependency Injection (DI). DI is the process by which objects are populated (injected) with values, called dependencies, usually coming from the IoC container itself. Basically, we have three options for that:

    • Constructor injection;
    • Property injection;
    • Method injection.

    What this means is, when asked for a particular instance, Unity will call a constructor, set a property’s value or invoke a method with a parameter coming from its registration. Say you have a class like this:

       1: public class MyService : IMyService
       2: {
       3:     public ILogger Logger
       4:     {
       5:         get;
       6:         private set;
       7:     }
       8:  
       9:     public MyService(ILogger logger)
      10:     {
      11:         this.Logger = logger;
      12:     }
      13:  
      14:     public void SetLogger(ILogger logger)
      15:     {
      16:         this.Logger = logger;
      17:     }
      18: }

    Unity can inject the Logger instance by either passing a parameter on the constructor when building an instance of the MyService class, directly setting the Logger property (even with a private setter) or by invoking the SetLogger method.

    Injection By Configuration

    As we have seen, most things in Unity can be configured by XML configuration:

       1: <register type="MyNamespace.IMyService, MyAssembly" mapTo="MyNamespace.MyService, MyAssembly">
       2:     <constructor>
       3:         <param name="logger" dependencyType="MyNamespace.ILogger, MyAssembly" dependencyName="File"/>
       4:     </constructor>
       5:     <property name="Logger" dependencyType="MyNamespace.ILogger, MyAssembly" dependencyName="File"/>
       6:     <method name="SetLogger">
       7:         <param name="logger" dependencyType="MyNamespace.ILogger, MyAssembly" dependencyName="File"/>
       8:     </method>
       9: </register>

    Did you notice the dependencyName attribute? That is the name under which the dependencyType was registered, if not set, it defaults to the empty string.

    I have included both constructor, property and method injection, you usually will only need one of them.

    Injection By Code

    Another option is by code. When registering a type, you must add some additional code:

       1: unity.RegisterType<IMyService, MyService>(new InjectionConstructor(unity.Resolve<ILogger>("File")), new InjectionMethod("SetLogger", unity.Resolve<ILogger>("File")), new InjectionProperty("Logger", unity.Resolve<ILogger>("File")));

    If you don’t want to resolve an instance yourself in InjectionMethod, InjectionConstructor or InjectionProperty, you can pass a Type and Unity will look up the actual instance for you.

    Injection By Attributes

    Another option is by applying attributes:

       1: public class MyService : IMyService
       2: {
       3:     [Dependency("File")]
       4:     public ILogger Logger
       5:     {
       6:         get;
       7:         private set;
       8:     }
       9:  
      10:     [InjectionConstructor]
      11:     public MyService([Dependency("File")] ILogger logger)
      12:     {
      13:         this.Logger = logger;
      14:     }
      15:  
      16:     [InjectionMethod]
      17:     public void SetLogger([Dependency("File")] ILogger logger)
      18:     {
      19:         this.Logger = logger;
      20:     }
      21: }

    The File string is the name of the registered type.

    Like previously mentioned, although I depicted all three, you will pick only one injection method. When you call Resolve or GetInstance, the instance you get will have its dependencies assigned.

    Injecting Dependencies On Existing Entities

    If you have some object instance that was obtained elsewhere, you can still ask Unity to inject whatever dependencies this object has. This is achieved by the BuildUp family of methods:

       1: IMyService svc = new MyService();
       2:  
       3: unity.BuildUp(svc);    //Logger property is set and SetLogger method is called

    Next in line: applying aspects. Stay tuned!

    Read more...

  • ASP.NET Web Forms Extensibility: Handler Factories

    An handler factory is the class that implements IHttpHandlerFactory and is responsible for instantiating an handler (IHttpHandler) that will process the current request. This is true for all kinds of web requests, whether they are for ASPX pages, ASMX/SVC web services, ASHX/AXD handlers, or any other kind of file. Also used for restricting access for certain file types, such as Config, Csproj, etc.

    Read more...