This post was sparked off by another post by Chris.
In his "Should classes by DI friendly?" post he talks about one DI issue he's having, the need to pass "other" configuration data to the object you want to DI. Let's take a quick tour of the issue at hand:
Say you have the following class
public class ServiceImplementation : IService{
public ServiceImplementation(ILog log){}
}
then the DI usage scenario becomes quite simple:
public class Usage{
public void Test(){
UnityContainer container = new UnityContainer();
IService svc = container.Resolve<IService>();
}
}
However, now add a requirement for an extra configuration parameter:
public class ServiceImplementation : IService{
public ServiceImplementation(ILog log, string someValue){}
}
Now, the question becomes: how can you add this extra information?
Configurator class
The first solution that comes to mind, an also one i tried to submit to his blog, but I'm not sure Feeddemon actually sent it ^^, is to add a new Configurator class which provides the necessary data and adding that configurator class as a constructor argument:
public class ServiceImplementationConfigurator{
public string GetSomeValue(){}
}
public class ServiceImplementation : IService{
public ServiceImplementation(ILog log, ServiceImplementationConfigurator configuration){}
}
The big advantage here is that you don't need to embark on a journey to subclass the unity container, you just add another dependency to the container. Disadvantage here is that your class depends on another object, but honestly I don't really mind this :)
As always, if you want to comment feel free :)
1 comments:
If your class needs to retrieve a lot of configuration options, it makes sense to inject some kind of ConfigurationProvider.
If you only need a few configuration options, the following approach might be a bit simpler:
http://ralinx.wordpress.com/2008/05/02/providing-configuration-data-with-windsor/
Post a Comment