Please skip to the UPDATE if you would like to just know the solution:
I have an application that uses the following code to get and run a number of worker methods
var type = typeof(IJob);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x => x.IsClass && type.IsAssignableFrom(x));
foreach (Type t in types)
{
IJob obj = Activator.CreateInstance(t) as IJob;
obj.Run();
}
This code works perfectly as is. However, some of the newer jobs utilize dependency injection to populate their constructors so this method will not be viable going forward. So I was wondering if there's a way to do this with unity?
My original thought was that I would continue with the first half and then replace the foreach logic with resolve so that it looks something like the following.
var type = typeof(IJob);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x => x.IsClass && type.IsAssignableFrom(x));
foreach (Type t in types)
{
IJob obj = Container.Resolve(t) as IJob;
obj.Run();
}
The problem is that as soon as I define my UnityContainer the returned types list that implement IJob suddenly gets bloated with all of these garbage Microsoft.Practices classes as shown below
UPDATE:
It turns out then when refelecting over Assemblies if Unity is present it will attempt to reflect into Unity's assemblies which if Finalized with a ToList will throw an exception due to a missing metadata extension of IServiceLocator. To work around this appending a where clause after GetAssemblies() to limit scope to your desired namespace will allow the application to run properly.
var type = typeof(IJob);
var types = AppDomain.CurrentDomain.GetAssemblies()
.Where(x => x.FullName.StartsWith("YourNamespace"))
.SelectMany(x => x.GetTypes())
.Where(x => x.IsClass && type.IsAssignableFrom(x));
foreach (Type t in types)
{
IJob obj = Container.Resolve(t) as IJob;
obj.Run();
}