Dynamic component resolution

Mar 7, 2013 at 7:14 AM
Is it possible to load the dependencies dynamicly? And if so how?

An example is given here under the title "Dynamic component resolution" : http://www.devtrends.co.uk/blog/how-not-to-do-dependency-injection-the-static-or-singleton-container

This way we can load the proper dependency based on configuration.
Coordinator
Mar 8, 2013 at 12:56 AM
There are two ways to accomplish this. The first is to use named registration
    container.Register<IColoredComponent, BlueComponent>("Blue");
    container.Register<IColoredComponent, RedComponent>("Red");

   ....

   string myFavoriteColor = ReadMyFavoriteColorFromConfigFIle();
   var coloredComponent = container.Resolve<IColoredComponent>(myFavoriteColor);
The other is to use the AutoRegistration feature of Munq.
If you call Munq.Configuration.ConfigurationLoader(IocContainer container), the dlls in the /bin directory will be searched for classes that implement the IMunqConfig interface.
An instance will be created of each of the classes found, and the RegisterIn(IocContainer container) method will be called. The class can then do whatever registration is required. Now you can configure your application by just dropping the 'correct' dll(s) into the \bin directory.
Mar 8, 2013 at 1:44 AM
Thanks for the answer.

I'll use the second option so I can remove the dependency to the layer with the concrete implementation.
Coordinator
Mar 8, 2013 at 2:59 AM
Personally, I rarely use the first option either. At the CodeProject, we use the second as well and it very nicely prevents the coupling caused by having to do all your registration in your top level executable. Your app really doesn't need to know what class is implementing the Interfaces.

Another variation is to create a Configuration project that just has a Class (or Classes) that implement the IMunqConfig Interface, and defines the IOC configuration. It is the only thing that needs to know about everything. Just drop this dll into the bin directory and you are configured.