We have created a WebApi solution using Autofac for DI. We broke out the bootstrapping of our autofac into a separate project. This way, our WebApi project only references our Bootstrap and Contracts projects. Our bootstrap project then references all other assemblies and wires everything together. I like this design for separation of concerns.
We can manually load our assemblies as follows - where our "AutofacModule" classes contain the necessary info to register each module (assembly).
ContainerBuilder builder = new Autofac.ContainerBuilder();
builder.RegisterModule(new Business.AutofacModule());
builder.RegisterModule(new Data.AutofacModule());
builder.RegisterModule(new Services.AutofacModule());
etc...
This works, but requires hardcoding each assembly. We are trying to make this dynamic so that we can just loop over all referenced assemblies as follows.
var assemblies = BuildManager.GetReferencedAssemblies().Cast<Assembly>();
foreach (var assembly in assemblies)
{
builder.RegisterAssemblyModules(assembly);
}
This should work but doesn't. The problem is that .Net determines various assemblies aren't actually used from within the bootstrap project and doesn't load them (in an attempt to optimize?). So some of our assemblies are never loaded.
I have also tried the following to loop through the bin directory to find all assemblies. However, during compilation, .Net doesn't move the non-referenced assemblies into the bin directory, so they aren't there either.
string assemblyPath = System.IO.Path.Combine(
System.AppDomain.CurrentDomain.BaseDirectory, "bin");
var allAssemblies = new List<Assembly>();
foreach (string dll in Directory.GetFiles(assemblyPath, "*.dll"))
{
allAssemblies.Add(Assembly.LoadFile(dll));
}
I have set the assemblies to Copy Local which didn't work. I read about a Copy Local bug and tried workarounds for that which didn't work either.
Has anyone been able to solve this issue? It seems like Autofac would provide a solution, but all I found was a To Do page on their documents: http://autofac.readthedocs.org/en/latest/faq/isolate-autofac.html
The following two questions are similar, but none of the proposed solutions overcome the fact that the needed assemblies are not in the bin directory.
Not all assemblies are being loaded into AppDomain from the bin folder
Loading all referenced assemblies .NET even if not used explicitly in code
Finally, I'm curious, is this an Autofac specific problem? How do other DI containers solve this problem? I found a similar problem for NInject. Loading unreferenced dll MVC Ninject