Multiple types with the same interface

Jul 3, 2010 at 2:12 PM

Is it possible to use Unity Auto Registration to register all implementations of a given interface, across multiple assembles? Because of the way that unity works, they will have to be given different names.

Jul 4, 2010 at 2:07 AM
Edited Jul 4, 2010 at 2:11 AM
Hi Anthony, It is possible. For example, I want to register all implementations of ILogger interface across all currently loaded assembles. As you've mentioned, we need to give different name to each registration, simplest way to do is is just use target type name. _container .ConfigureAutoRegistration() .Include(If.Implements<ILogger>, Then.Register().As<ILogger>().WithTypeName()) .ApplyAutoRegistration(); If type name is not something that you want to use as registration name, then you do for example: _container .ConfigureAutoRegistration() .Include(If.Implements<ILogger>, Then.Register().As<ILogger>().WithName(type => type.Assembly.FullName)) .ApplyAutoRegistration(); This way you'll be using Assembly FullName as registration name. As you see WithName method takes lambda as parameter, so you can create your own rule to produce registration name from given type being registred. If you have external assemblies that are not loaded yet by the time you are running auto registration (for example because currently executing assembly doesn't reference them directly or because you haven't used any type from these assemblies yet, so they are non loaded by the time you are running auto registration), in this case you can load them explicitly before registration. So if I have ILogger implementation in my current assembly plus a couple of implementations in ExternalAssembly.dll that I wanted to register, then my first example would look like: _container .ConfigureAutoRegistration() .LoadAssemblyFrom("ExternalAssembly.dll") /* or LoadAssemblies(list of assemblies) */ .Include(If.Implements<ILogger>, Then.Register().As<ILogger>().WithTypeName()) .ApplyAutoRegistration();
Jul 5, 2010 at 8:54 AM

Thanks. That last bit of code is very similar to what we want to do - i.e. find some Dlls in a folder, and build up an instance of each type that implements a specific interface, using Unity to put values into the constructor.