Contents tagged with IoC

  • Unity, Part 9: Integration With Managed Extensibility Framework

    This time, I will be talking about integrating Unity with Managed Extensibility Framework (MEF). You can find the other posts in the series here (how to use Unity in a web application), here (adding Interfaces), here (registration by convention), here (injecting values), here (extensions), here (aspect-oriented programming), here (dependency injection) and the first one here (introduction).

    The Managed Extensibility Framework (MEF) has been around since the release of .NET 4.0, and even before as a beta, stand-alone package. Basically, it provides an extensible mechanism for detecting and loading plugins. It’s easier to use than the similarly-named Managed Add-In Framework (MAF), and even if it’s not so feature-rich (it doesn’t support sandboxing, for once), unlike MAF, it is well alive!

    So, what does MEF offer that can be of use to Unity? Well, MEF knows how to locate exports/plugins from a number of locations, like assemblies and file system directories. It’s just a matter of finding the exports we’re interested in and registering them with Unity.

    An export in MEF is some class that is decorated with an ExportAttribute (technically speaking, this is just when using the Attributed Programming Model, since .NET 4.5 there is also the Convention-Based Programming Model). This attribute allows specifying the type to export (ContractType) and also the contract name (ContractName). This matches closely the Unity/IoC concept of contract type and name.

    We could find all exports under a given path using MEF using an AssemblyCatalog, a particular implementation of a ComposablePartCatalog:

       1: var catalog = new AssemblyCatalog("some path");

    A couple of helper functions for picking up the export’s contract type and name, by leveraging the ReflectionModelServices class:

       1: public static IDictionary<String, Type> GetExportedTypes<T>(this ComposablePartCatalog catalog)
       2: {
       3:     return (GetExportedTypes(catalog, typeof(T)));
       4: }
       6: public static IDictionary<String, Type> GetExportedTypes(this ComposablePartCatalog catalog, Type type)
       7: {
       8:     return (catalog.Parts.Where(part => IsComposablePart(part, type) == true).ToDictionary(part => part.ExportDefinitions.First().ContractName, part => ReflectionModelServices.GetPartType(part).Value));
       9: }
      12: private static Boolean IsComposablePart(ComposablePartDefinition part, Type type)
      13: {
      14:     return (part.ExportDefinitions.Any(def => (def.Metadata.ContainsKey("ExportTypeIdentity") == true) && (def.Metadata["ExportTypeIdentity"].Equals(type.FullName) == true)));
      15: }

    This will return a collection of key-value pairs, where the key is the contract name and the value the contract type; this is so there can be multiple contract names for a given contract type. After we have this, it’s just a matter of iterating the results and registering each occurrence:

       1: var type = typeof(ISomeType);
       2: var exports = catalog.GetExportedTypes(type);
       4: foreach (var entry in exports)
       5: {
       6:     unity.RegisterType(type, entry.Value, entry.Key);
       7: }

    So, given the following contract and implementations:

       1: public interface ISomeType
       2: {
       3:     void SomeMethod();
       4: }
       6: [Export("Some", typeof(ISomeType))]
       7: public class SomeImplementation : ISomeType
       8: {
       9:     public void SomeMethod() { }
      10: }
      12: [Export("Another", typeof(ISomeType))]
      13: public class AnotherImplementation : ISomeType
      14: {
      15:     public void SomeMethod() { }
      16: }

    We can obtain a specific contract type implementation given it’s name:

       1: var myImplementation = unity.Resolve<ISomeType>("MyName");

    And also all implementations of the contract that were found:

       1: var all = unity.ResolveAll<ISomeType>();

    This can be enhanced in a couple of ways:

    • Use a Unity extension to automatically find and register exports at runtime;
    • Make use of MEF metadata to tell Unity which lifetime managers to use, and other useful properties, such as the default implementation for the contract type.

    As usual, I’m looking forward for your comments!


  • Unity - Part 8: Web


    Long overdue in the Unity series, how to use Unity in a web application. You can find the other posts here (Adding Interfaces), here (Registration by Convention), here (Injecting Values), here (Extensions), here (Aspect-Oriented Programming), here (Dependency Injection) and here (Introduction).

    Lifetime Management

    So, you want to store instances in the current web request, so that they are only available during the request. The problem is, there is no out of the box functionality in Unity that allows you to do that.

    First, you will want to add the Unity.Mvc NuGet package:


    This gives you a new lifetime manager, PerRequestLifetimeManager, which stores the request in the HttpContext.Current.Items collection. So, in the beginning of the request, you can register an instance using it:

    1: unity.RegisterInstance<ILogger>(new FileLogger(“output.log”),

    new PerRequestLifetimeManager());

    Or you can also register a type, even in Application_Start, because it will only be resolved when explicitly asked for:

       1: unity.RegisterType<ILogger, FileLogger>(new PerRequestLifetimeManager());

    The problem with this approach is that entities instantiated by Unity that implement IDisposable will not be disposed of automatically at the end of the request. For that, we need something else: UnityPerRequestHttpModule. Since this is a regular IHttpModule, we can register it on the Web.config file. What it does is, at the end of the request, it iterates through all of the instances that Unity created using the PerRequestLifetimeManager which happen to be IDisposable and will dispose of them. Mind you, even if this comes in a package called Unity.Mvc, you can certainly use it with Web Forms.

    Dependency Resolution

    MVC uses it’s own dependency resolution facility, DependencyResolver. Unity.Mvc includes an adapter for it, UnityDependencyResolver, that you use as this:

       1: DependencyResolver.SetResolver(new UnityDependencyResolver(unity));

    This way, whenever MVC needs to resolve one of its components, it will delegate this to Unity.


    ASP.NET MVC has the concept of filters, which offer a sort of Aspect-Oriented Programming model. Filters can be applied to either action methods or the whole controller, and can be of the following kind:

    Normally, these filters are either applied through an attribute or globally. The UnityFilterAttributeFilterProvider class can be used to retrieve filters registered in Unity instead. You use it as:

       1: var oldProvider = FilterProviders.Providers.SingleOrDefault(f => f is FilterAttributeFilterProvider);
       3: if (oldProvider != null)
       4: {
       5:     FilterProviders.Providers.Remove(oldProvider);
       6: }
       8: FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(unity));

    If you have registered components that implement one of the filter interfaces, they will be injected automatically.

    Creating Controllers

    The class that MVC uses to create controllers is DefaultControllerFactory. It does its job by inspecting the well-known Controllers namespace of the containing web application assembly. We can create a class that inherits from DefaultControllerFactory and first tries to lookup the controller from Unity:

       1: public class UnityControllerFactory : DefaultControllerFactory
       2: {
       3:     private readonly IUnityContainer unity;
       5:     public UnityControllerFactory(IUnityContainer unity)
       6:     {
       7:         this.unity = unity;
       8:     }
      10:     public override IController CreateController(RequestContext requestContext, string controllerName)
      11:     {
      12:         var controller = unity.Resolve<IController>(controllerName);
      14:         if (controller == null)
      15:         {
      16:             controller = base.CreateController(requestContext, controllerName);
      17:         }
      19:         if (controller != null)
      20:         {
      21:             unity.BuildUp(controller.GetType(), controller);
      22:         }
      24:         return (controller);
      25:     }
      26: }

    And for the registration:

       1: ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(unity));

    Model Binding

    Model binding occurs when you call an action method that takes as one of its parameters a class. MVC automatically creates a class of the proper type, but you can add Unity to the loop, in cases where it is not so easy to achieve. For example, consider an action method that receives an ILogger instance. By applying a custom model binder (IModelBinder), you can have MVC resolve it automatically:

       1: public sealed class UnityModelBinder : IModelBinder
       2: {
       3:     private readonly IUnityContainer unity;
       5:     public UnityModelBinder(IUnityContainer unity)
       6:     {
       7:         this.unity = unity;
       8:     }
      10:     #region IModelBinder Members
      12:     public Object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
      13:     {
      14:         return (this.unity.Resolve(bindingContext.ModelType));
      15:     }
      17:     #endregion
      18: }

    Its registration:

       1: ModelBinders.Binders.Add(typeof(ILogger), new UnityModelBinder(unity));

    You can add as many types as you like, MVC will try each of them until one returns a valid instance.


  • Unity – Part 6: Registration by Convention


    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;
       6:     public InterfaceToTypeConvention(IUnityContainer unity, params Assembly [] assemblies) : this(unity, assemblies.SelectMany(a => a.GetExportedTypes()).ToArray())
       7:     {
       8:         this.unity = unity;
       9:     }
      11:     public InterfaceToTypeConvention(IUnityContainer unity, params Type[] types)
      12:     {
      13:         this.unity = unity;
      14:         this.types = types ?? Enumerable.Empty<Type>();
      15:     }
      17:     public override Func<Type, IEnumerable<Type>> GetFromTypes()
      18:     {
      19:         return (WithMappings.FromAllInterfacesInSameAssembly);
      20:     }
      22:     public override Func<Type, IEnumerable<InjectionMember>> GetInjectionMembers()
      23:     {
      24:         return (x => Enumerable.Empty<InjectionMember>());
      25:     }
      27:     public override Func<Type, LifetimeManager> GetLifetimeManager()
      28:     {
      29:         return (WithLifetime.ContainerControlled);
      30:     }
      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:     }
      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.


    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!


  • Sending Messages to SignalR Hubs from the Outside


    You are by now probably familiarized with SignalR, Microsoft’s API for real-time web functionality. This is, in my opinion, one of the greatest products Microsoft has released in recent time.

    Usually, people login to a site and enter some page which is connected to a SignalR hub. Then they can send and receive messages – not just text messages, mind you – to other users in the same hub. Also, the server can also take the initiative to send messages to all or a specified subset of users on its own, this is known as server push.

    The normal flow is pretty straightforward, Microsoft has done a great job with the API, it’s clean and quite simple to use. And for the latter – the server taking the initiative – it’s also quite simple, just involves a little more work.

    The Problem

    The API for sending messages can be achieved from inside a hub – an instance of the Hub class – which is something that we don’t have if we are the server and we want to send a message to some user or group of users: the Hub instance is only instantiated in response to a client message.

    The Solution

    It is possible to acquire a hub’s context from outside of an actual Hub instance, by calling GlobalHost.ConnectionManager.GetHubContext<T>(). This API allows us to:

    • Broadcast messages to all connected clients (possibly excluding some);
    • Send messages to a specific client;
    • Send messages to a group of clients.

    So, we have groups and clients, each is identified by a string. Client strings are called connection ids and group names are free-form, given by us. The problem with client strings is, we do not know how these map to actual users.

    One way to achieve this mapping is by overriding the Hub’s OnConnected and OnDisconnected methods and managing the association there. Here’s an example:

       1: public class MyHub : Hub
       2: {
       3:     private static readonly IDictionary<String, ISet<String>> users = new ConcurrentDictionary<String, ISet<String>>();
       5:     public static IEnumerable<String> GetUserConnections(String username)
       6:     {
       7:         ISet<String> connections;
       9:         users.TryGetValue(username, out connections);
      11:         return (connections ?? Enumerable.Empty<String>());
      12:     }
      14:     private static void AddUser(String username, String connectionId)
      15:     {
      16:         ISet<String> connections;
      18:         if (users.TryGetValue(username, out connections) == false)
      19:         {
      20:             connections = users[username] = new HashSet<String>();
      21:         }
      23:         connections.Add(connectionId);
      24:     }
      26:     private static void RemoveUser(String username, String connectionId)
      27:     {
      28:         users[username].Remove(connectionId);
      29:     }
      31:     public override Task OnConnected()
      32:     {
      33:         AddUser(this.Context.Request.User.Identity.Name, this.Context.ConnectionId);
      34:         return (base.OnConnected());
      35:     }
      37:     public override Task OnDisconnected()
      38:     {
      39:         RemoveUser(this.Context.Request.User.Identity.Name, this.Context.ConnectionId);
      40:         return (base.OnDisconnected());
      41:     }
      42: }

    As you can see, I am using a static field to store the mapping between a user and its possibly many connections – for example, multiple open browser tabs or even multiple browsers accessing the same page with the same login credentials. The user identity, as is normal in .NET, is obtained from the IPrincipal which in SignalR hubs case is stored in Context.Request.User. Of course, this property will only have a meaningful value if we enforce authentication.

    Another way to go is by creating a group for each user that connects:

       1: public class MyHub : Hub
       2: {
       3:     public override Task OnConnected()
       4:     {
       5:         this.Groups.Add(this.Context.ConnectionId, this.Context.Request.User.Identity.Name);
       6:         return (base.OnConnected());
       7:     }
       9:     public override Task OnDisconnected()
      10:     {
      11:         this.Groups.Remove(this.Context.ConnectionId, this.Context.Request.User.Identity.Name);
      12:         return (base.OnDisconnected());
      13:     }
      14: }

    In this case, we will have a one-to-one equivalence between users and groups. All connections belonging to the same user will fall in the same group.

    So, if we want to send messages to a user from outside an instance of the Hub class, we can do something like this, for the first option – user mappings stored in a static field:

       1: public void SendUserMessage(String username, String message)
       2: {
       3:     var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
       5:     foreach (String connectionId in HelloHub.GetUserConnections(username))
       6:     {
       7:         context.Clients.Client(connectionId).sendUserMessage(message);
       8:     }
       9: }

    And for using groups, its even simpler:

       1: public void SendUserMessage(String username, String message)
       2: {
       3:     var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
       5:     context.Clients.Group(username).sendUserMessage(message);
       6: }

    Using groups has the advantage that the IHubContext interface returned from GetHubContext has direct support for groups, no need to send messages to individual connections.

    Of course, you can wrap both mapping options in a common API, perhaps exposed through IoC. One example of its interface might be:

       1: public interface IUserToConnectionMappingService
       2: {
       3:     //associate and dissociate connections to users
       5:     void AddUserConnection(String username, String connectionId);
       7:     void RemoveUserConnection(String username, String connectionId);
       8: }

    SignalR has built-in dependency resolution, by means of the static GlobalHost.DependencyResolver property:

       1: //for using groups (in the Global class)
       2: GlobalHost.DependencyResolver.Register(typeof(IUserToConnectionMappingService), () => new GroupsMappingService());
       4: //for using a static field (in the Global class)
       5: GlobalHost.DependencyResolver.Register(typeof(IUserToConnectionMappingService), () => new StaticMappingService());
       7: //retrieving the current service (in the Hub class)
       8: var mapping = GlobalHost.DependencyResolver.Resolve<IUserToConnectionMappingService>();

    Now all you have to do is implement GroupsMappingService and StaticMappingService with the code I shown here and change SendUserMessage method to rely in the dependency resolver for the actual implementation.

    Stay tuned for more SignalR posts!


  • Unity – Part 5: Injecting Values


    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.


    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:     }
       9:     #region ILogger Members
      11:     public void Log(String message)
      12:     {
      13:         using (Stream file = File.OpenWrite(this.Filename))
      14:         {
      15:             Byte[] data = Encoding.Default.GetBytes(message);
      17:             file.Write(data, 0, data.Length);
      18:         }
      19:     }
      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];
       8:         if (parameterType != typeof(String))
       9:         {
      10:             TypeConverter typeConverter = this.GetTypeConverter(parameterType);
      12:             configurationValue = typeConverter.ConvertFromInvariantString(configurationValue as String);
      13:         }
      15:         return (configurationValue);
      16:     }
      17:     #endregion
      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
      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
      41:     #region IDependencyResolverPolicy Members
      43:     public Object Resolve(IBuilderContext context)
      44:     {
      45:         Type parameterType = null;
      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:         }
      71:         return (this.CreateInstance(parameterType));
      72:     }
      74:     #endregion
      76:     #region Public properties
      77:     [ConfigurationProperty("appSettingsKey", IsRequired = true)]
      78:     public String AppSettingsKey
      79:     {
      80:         get
      81:         {
      82:             return ((String)base["appSettingsKey"]);
      83:         }
      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="">
       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="">
       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:     }
      10:     public String TypeConverterTypeName
      11:     {
      12:         get;
      13:         set;
      14:     }
      16:     public String AppSettingsKey
      17:     {
      18:         get;
      19:         private set;
      20:     }
      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:     }
      10:     #region ILogger Members
      12:     public void Log(String message)
      13:     {
      14:         using (Stream file = File.OpenWrite(this.Filename))
      15:         {
      16:             Byte[] data = Encoding.Default.GetBytes(message);
      18:             file.Write(data, 0, data.Length);
      19:         }
      20:     }
      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:     }
       9:     public FileLogger([AppSettingsDependencyResolution("LoggerFilename")] String filename)
      10:     {
      11:         this.Filename = filename;
      12:     }
      14:     #region ILogger Members
      16:     public void Log(String message)
      17:     {
      18:         using (Stream file = File.OpenWrite(this.Filename))
      19:         {
      20:             Byte[] data = Encoding.Default.GetBytes(message);
      22:             file.Write(data, 0, data.Length);
      23:         }
      24:     }
      26:     #endregion
      27: }


    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.


  • Unity – Part 4: 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
      15:     #region Protected override methods
      16:     protected override void Initialize()
      17:     {
      18:         base.Initialize();
      20:         IConfigurationSource configSource = ConfigurationSourceFactory.Create();
      21:         PolicyInjectionSettings section = configSource.GetSection(PolicyInjectionSettings.SectionName) as PolicyInjectionSettings;
      23:         if (section != null)
      24:         {
      25:             section.ConfigureContainer(this.Container, configSource);
      26:         }
      28:         this.Context.Registering += delegate(Object sender, RegisterEventArgs e)
      29:         {                
      30:             this.setInterceptorFor(e.TypeFrom, e.TypeTo, e.Name, e.LifetimeManager);
      31:         };
      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
      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:                 }
      56:                 //add a custom behavior for all types
      58:                 break;
      59:             }
      60:         }
      61:     }
      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 = ...;
       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="">
       6:         <container>
       7:             <extension type="MyNamespace.DefaultInterception, MyAssembly"/>
       8:         </container>
       9:     </unity>
      10: </configuration>


    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!


  • Unity – Part 3: Aspect Oriented Programming


    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:


    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="">
       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:     }
       9:     public Boolean After
      10:     {
      11:         get;
      12:         set;
      13:     }
      15:     public String Message
      16:     {
      17:         get;
      18:         set;
      19:     }
      21:     Int32 ICallHandler.Order
      22:     {
      23:         get;
      24:         set;
      25:     }
      27:     IMethodReturn ICallHandler.Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
      28:     {
      29:         if (this.Before == true)
      30:         {
      31:             Console.WriteLine(this.Message);
      32:         }
      34:         IMethodReturn result = getNext()(input, getNext);
      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:         }
      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:     }
       8:     IMethodReturn IInterceptionBehavior.Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
       9:     {
      10:         //before target method call
      12:         if (input.MethodBase == typeof(MyService).GetMethod("DoSomething"))
      13:         {
      14:             //do something
      15:         }
      17:         IMethodReturn methodReturn = getNext().Invoke(input, getNext);
      19:         //after target method call
      21:         return (methodReturn);
      22:     }
      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:     }
      11:     public Boolean After
      12:     {
      13:         get;
      14:         set;
      15:     }
      17:     public String Message
      18:     {
      19:         get;
      20:         private set;
      21:     }
      23:     public OutputCallHandlerAttribute(String message)
      24:     {
      25:         this.Message = message;
      26:     }
      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="">
       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>


    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.


  • 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:     }
       9:     public MyService(ILogger logger)
      10:     {
      11:         this.Logger = logger;
      12:     }
      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:     }
      10:     [InjectionConstructor]
      11:     public MyService([Dependency("File")] ILogger logger)
      12:     {
      13:         this.Logger = logger;
      14:     }
      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();
       3: unity.BuildUp(svc);    //Logger property is set and SetLogger method is called

    Next in line: applying aspects. Stay tuned!