I’m using the IUnityContainer from the Composite Application Guidance in my current Silverlight project for Dependency Injection and this morning, I came across something that I couldn’t find documented anywhere. Initially, all my registered dependencies were being created using other dependencies that I had registered with the container. For example, I had the CustomerOrderService below and it was created using an IEventAggregator that was already registered in the container.
public class CustomerOrderService : ICustomerOrderService { public CustomerOrderService(IEventAggregator evAg) { this.eventAggregator = evAg; } }
I was just registering my service with the container and letting it do all the work.
this.container.RegisterType();
However, this morning, I wanted to add a simple string to my constructor so that I could pass in the URI for a web service instead of hard coding it in the service class. After digging around a little in the docs and eventually just playing with the code until it worked, I came up with two ways of doing this.
First, I modified my service to have two constructor arguments:
public class CustomerOrderService : ICustomerOrderService { public CustomerOrderService(IEventAggregator evAg, string uri) { this.eventAggregator = evAg; this.baseUri = uri; } }
Then, I came up with the two ways to register this service in code with the container. First, you can tell the container how to configure your dependency registration.
this.container.Configure().ConfigureInjectionFor ( new InjectionConstructor(typeof(IEventAggregator), "URI GOES HERE"));
When the container is asked to create a CustomerOrderService object, it is configured to send in an IEventAggregator instance that it resolves internally and the URI string above. Of course, in a real world app, that URI would actually be a URI that I get from configuration.
Alternatively, you can tell the container what to do when you register the type:
this.container.RegisterType( new InjectionConstructor(typeof(IEventAggregator), "URI GOES HERE"));
This is a little cleaner because you’re going to have to register the type anyway and it makes sense to configure it at the same time.
By allowing the developer to specify an InjectionConstructor to use, the UnityContainer gives the developer a much more flexible way to register his dependencies.
PS: The Google Syntax highlighter and my new WordPress theme don’t apparently play well together. Or at all. So the code is displaying in a ridiculous way. If you need an actual example, feel free to drop me a line in the comments and I’ll send you one. It may be time to separate my tech blogging out from The Experiment.