# Monday, June 07, 2010
« Windows AppFabric Hits the Streets | Main | Software Architect Conference 2010 »

I’ve been working with the Unity IoC container from Microsoft Patterns and Practices recently. Its mostly straightforward as IoC containers go but one thing had me puzzled for a while as its not really documented or blogged as far as I can see; so I decided to blog it so hopefully others looking will stumble across this article

Lets start off with a simple example: I have two interfaces: IService and IRepository that live in the Interfaces class library

   1: public interface IService
   2: {
   3:     void DoWork();
   4: }
   1: public interface IRepository
   2: {
   3:     string GetStuff();
   4: }
I also have two implementations in the Services class library: MyRepository 
   1: public class MyRepository : IRepository
   2: {
   3:     public string GetStuff()
   4:     {
   5:         return "TADA!!";
   6:     }
   7: }

and MyService

   1: public class MyService : IService
   2: {
   3:     private IRepository repository;
   4:  
   5:     public MyService(IRepository repository)
   6:     {
   7:         this.repository = repository;
   8:     }
   9:     public void DoWork()
  10:     {
  11:         Console.WriteLine(repository.GetStuff());
  12:     }
  13: }

Notice that MyService needs an IRepository to do its work. Now the idea here is I’m going to wire this together via dependency injection and the Unity IoC container. So I have my application

   1: class Program
   2: {
   3:     static void Main(string[] args)
   4:     {
   5:         UnityContainer container = new UnityContainer();
   6:         UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
   7:         section.Configure(container);
   8:  
   9:         IService svc = container.Resolve<IService>();
  10:  
  11:         svc.DoWork();
  12:     }
  13: }

Notice as we’re using IoC that there are no hard coded dependencies – everything is wired up via the container. However, there must be some information about how the interfaces map to concrete types and this is in the config file

   1: <configuration>
   2:   <configSections>
   3:     <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
   4:   </configSections>
   5:  
   6:   <unity>
   7:     <typeAliases>
   8:       <!-- Lifetime Managers -->
   9:       <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager"/>
  10:  
  11:       <!-- Interfaces -->
  12:       <typeAlias alias="IService" type="Interfaces.IService,Interfaces"/>
  13:       <typeAlias alias="IRepository" type="Interfaces.IRepository,Interfaces"/>
  14:  
  15:       <!-- Implementations -->
  16:       <typeAlias alias="service" type="Services.MyService, Services"/>
  17:       <typeAlias alias="repository" type="Services.MyRepository, Services"/>
  18:  
  19:     </typeAliases>
  20:     <containers>
  21:       <container>
  22:         <types>
  23:           <type type="IService" mapTo="service">
  24:             <lifetime type="singleton"/>
  25:           </type>
  26:           <type type="IRepository" mapTo="repository">
  27:             <lifetime type="singleton"/>
  28:           </type>
  29:         </types>
  30:       </container>
  31:     </containers>
  32:   </unity>
  33: </configuration>

Now all of this works fine and is simple Unity stuff. We use constructor injection to get the repository implementation into the service constructor. However, I’ve decided the service needs a timeout that I will generally configure in the config file. However to make Unit Testing simple I’ll add another constructor to MyService so I can pass a specific timeout

   1: public class MyService : IService
   2: {
   3:     private IRepository repository;
   4:     TimeSpan timeout;
   5:  
   6:     public MyService(IRepository repository, TimeSpan timeout)
   7:     {
   8:         this.timeout = timeout;
   9:     }
  10:     
  11:     public MyService(IRepository repository)
  12:     {
  13:         this.repository = repository;
  14:         timeout = GetTimeoutFromConfig();
  15:     }
  16:  
  17:     private TimeSpan GetTimeoutFromConfig()
  18:     {
  19:         return default(TimeSpan);
  20:     }
  21:  
  22:     public void DoWork()
  23:     {
  24:         Console.WriteLine(repository.GetStuff());
  25:     }
  26: }

Now I try to run the application and I get a pretty ugly error

Unhandled Exception: Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed,
type = "Interfaces.IService", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type Int32 cannot be constructed.
You must configure the container to supply this value.

Now that’s weird – I have no types that take an Int32! This is caused by Unity’s default behavior where it will try to resolve on the constructor with the most parameters (on the basis that this one will have the most dependencies that can be injected). It tried to resolve the TimeSpan and so looks at the TimeSpan and tries to resolve its constructor which can take an Int32. I actually want to tell it to use a different constructor and I can do this in two ways: annotate the constructor I want to use with the [InjectionConstructor] attribute

   1: [InjectionConstructor]
   2: public MyService(IRepository repository)
   3: {
   4:     this.repository = repository;
   5:     timeout = GetTimeoutFromConfig();
   6: }

But personally I don’t like this. It forces the services assembly to take a dependency on Unity and the service has knowledge about how its being constructed. What I really want to do is specify this in config. This isn’t very well documented from what I can see but what you do it specify the constructor and how to resolve the parameters against the type mapping in the config – i.e.

   1: <type type="IService" mapTo="service">
   2:   <lifetime type="singleton"/>
   3:   <constructor>
   4:     <param name="repository">
   5:       <dependency/>
   6:     </param>
   7:   </constructor>
   8: </type>

As well as specifying dependencies you can also give explicit values by using <value/> instead of <dependency/>. This model I think is a lot cleaner than the attribute approach.