Contents tagged with IoC
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.
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:
- 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;
So, here’s an example of the first approach:
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:
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:
And its registration:
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!
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 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.
- 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.
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:
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:
And for using groups, its even simpler:
Of course, you can wrap both mapping options in a common API, perhaps exposed through IoC. One example of its interface might be:
SignalR has built-in dependency resolution, by means of the static GlobalHost.DependencyResolver property:
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!
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:
And a concrete implementation that writes to a file:
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.
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”:
And on the configuration file, for setting a property, we use it like this:
If we would like to inject the value as a constructor parameter, it would be instead:
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:
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:
Or, if we wanted to use constructor injection:
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 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:
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
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:
In both cases, if the extension needs configuring, you can access it by using the Configure method:
This will only return the already registered extension, not create a new one.
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!
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:
Or by XML configuration:
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:
Authorization handler (Microsoft.Practices.EnterpriseLibrary.Security.PolicyInjection.AuthorizationCallHandler): for implementing authorization rules;
Exception handling handler (Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.PolicyInjection.ExceptionCallHandler): for applying the rules of the Exception Handling application block;
Logging handler (Microsoft.Practices.EnterpriseLibrary.Logging.PolicyInjection.LogCallHandler): for logging calls before and after a method call using the Logging application block;
Validation handler (Microsoft.Practices.EnterpriseLibrary.Validation.ValidationCallHandler): for validating arguments of a method with the Validation application block;
Performance counter handler (Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.PerformanceCounterCallHandler): for updating a performance counter upon calling a method.
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:
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:
If we want to cancel the default method call, if it is non void, we must return an appropriate value:
Or if we want to return an exception:
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:
And we apply it to any method declaration:
But before this works, we need to tell Unity to use interface interception for our type:
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:
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:
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:
Next in line: extending Unity.
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:
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:
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:
Injection By Attributes
Another option is by applying attributes:
The File string is the name of the registered type.
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:
Next in line: applying aspects. Stay tuned!
Updated: ContainerControlled instead of ExternallyControlled in the bullet list of lifetime managers. Thanks, Ross Smith!