Instantiating multiple instances of a container from xml

Aug 4, 2014 at 8:07 PM
Very new to Unity and IoC in general so after a bit of a crash course I have a question (or 2)...

Some back ground first.
I am creating a service that will communicate with external devices using various protocols; a legacy protocol for existing devices, a new protocol for next generation devices, and one or more third party device protocols.

I was heading down a path where I was writing various adapters that supported a common interface and were configured in an XML file. The service will instantiate an instance of each configured adapter and they would operate independently. The configuration includes the namespace and class name and I am using Activator.CreateInstance from the .NET framework to create the classes. Seems to work OK but someone suggested I look into DI and Unity so after looking at some Plural Sight videos I can see some of the benefits in this approach.

The Question
Given the above scenario, Can I use Unity and an external configuration files and achieve the same results of instantiating multiple adapters that use the same interface but are different class implementations? In other words, can I create a variable set of containers for the interface?

Not sure I asked that correctly, Thanks!
Aug 10, 2014 at 7:26 PM
Yes, you can configure Unity (using XML) with various concrete implementations of the same interface. To do this you would associate each registration with a name (the concrete class name is common but you can use any name). The question is how does the service know what implementation of the interface to use? One approach would be to inject the appropriate dependency by name; another approach would be to use a factory (or Unity InjectionFactory) to determine what instance to return/inject.

I know that's pretty high level but I hope that it helps. I would do some reading and do some testing (maybe stick with code based configuration before moving onto the slightly more complicated XML configuration) and post back any specific questions you encounter.

~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to