# Monday, June 07, 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.
Monday, June 07, 2010 11:14:26 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |   | 
.NET | Dublin | WCF | WF
Monday, June 07, 2010 10:05:40 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |   | 

The Visual Studio 2010 Power Tools have just been released. There’s all sorts of goodness in here: new flexible tab handling in the VS shell (vertical tab groups, tabs grouped by project, dropping of rarely used tabs, etc); a new searchable Add Reference dialog; new editor enhancements to make navigation easier and much more

I’ve been playing with it for the last couple of hours and its very neat. Of course I don’t use Resharper or CodeRush (I use too many machines I don’t control to become dependent on them) so some of these features may be available in those tools. But for me the power tools are a welcome addition to the IDE

.NET | VS
Monday, June 07, 2010 8:26:40 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |   | 
# Tuesday, March 30, 2010

Rock Solid Knowledge on iTunes is live! We’ve taken the feed to our free screencasts and they are now available through iTunes via the following link

http://itunes.apple.com/gb/podcast/rock-solid-knowledge-screencasts/id365244375

Now you can watch them on the move

.NET | EF4 | PFx | RSK | SilverLight | WCF | WF | WF4
Tuesday, March 30, 2010 9:13:22 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |   | 
# Wednesday, March 17, 2010

Thanks to everyone who attended my sessions at DevWeek 2010. I’ve now uploaded the demos which you can find at the following locations

A Day of .NET 4.0 Demos

Windows Workflow Foundation 4.0 Demos

Creating WCF Services using WF4 Demos

I’ll be around for the rest of the conference so drop by for a chat at our developer clinic in the exhibition area

.NET | EF4 | RSK | WCF | WF | WF4
Wednesday, March 17, 2010 8:13:59 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   | 
# Wednesday, March 10, 2010

In my last post I pointed to a screencast I had recorded that showed how to create a custom message filter to plug your own logic into the WCF 4.0 Routing Service. However, the simple custom filter is only the start – you can actually take control of part of the routing table which allows you to make global decisions about which filters match a particular request. On that basis I have created another screencast that shows how to build one of these more complex custom filters. in this case I use the example of a round robin load balancer where you can use a file on the file system to indicate whether a specific endpoint should be considered part of the load balancing algorithm

You can find this last in the series of screencasts on the routing service, along with all the others here, on the Rock Solid Knowledge site

http://rocksolidknowledge.com/ScreenCasts.mvc

.NET | RSK | WCF
Wednesday, March 10, 2010 1:05:40 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   | 
# Monday, March 08, 2010

I’ve just uploaded a new screencast on the the Rock Solid Knowledge site. This one shows you how to plug your own routing logic into the new Routing Service that is part of WCF 4.0. It uses a custom message filter that can be used to supplement the existing set of filters such as matching on XPath and Action.

You can find the screencast (along with the previous ones in the series) here

http://www.rocksolidknowledge.com/ScreenCasts.mvc

.NET | WCF
Monday, March 08, 2010 12:37:22 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   | 
# Tuesday, March 02, 2010

Continuing my screencast series on the Routing Service in WCF 4.0, I have just uploaded one on Data Dependent Routing

You can get to the latest screencast (and all of the others) here http://rocksolidknowledge.com/ScreenCasts.mvc

.NET | RSK | WCF
Tuesday, March 02, 2010 10:50:18 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   | 
# Monday, March 01, 2010

I have just published my second screencast on one of the new features of WCF 4.0 – the Routing Service. This screencast focuses on enabling multicast and failover with the Routing Service

You can get to the screencast from here http://rocksolidknowledge.com/ScreenCasts.mvc

.NET | RSK | WCF
Monday, March 01, 2010 1:16:51 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   | 
# Friday, February 26, 2010

Thanks to everyone who attended my two sessions at BASTA! – another thoroughly enjoyable conference. I’ve uploaded the demos

What’s new in Workflow 4.0 – this includes the application with the rehosted designer

Building WCF services with Workflow 4.0

.NET | WCF | WF | WF4
Friday, February 26, 2010 10:02:42 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   |