问题
Let's say you're working on an ASP.NET MVC project and it is layers split up into different projects in a single solution. Each project has autofac modules created to wire up the dependencies. Now, I would like to scan the assemblies and register all of the modules into the container.
I adapted an extension method similar to what was shared here http://goo.gl/VJEct
public static void RegisterAssemblyModules(this ContainerBuilder builder, Assembly
assembly)
{
var scanningBuilder = new ContainerBuilder();
scanningBuilder.RegisterAssemblyTypes(assembly)
.Where(t => typeof(IModule).IsAssignableFrom(t))
.As<IModule>();
using (var scanningContainer = scanningBuilder.Build())
{
foreach (var m in scanningContainer.Resolve<IEnumerable<IModule>>())
builder.RegisterModule(module);
}
}
My first question, considering that this sample was provided a few years ago, is this still an feasible construct to use with current versions of autofac?
Secondly, the MVC app is dependent on functionality in the other layers which means at times I would need to register types with .InstancePerHttpRequest(). However, I would also like to have the option of referencing them from non web applications and not take a dependency on System.Web. What is the best approach for to register modules that can be used in these different contexts?
回答1:
I would not register the modules in the container. I see no reason to do that.
Here is an alternative.
It uses Activator.CreateInstance
to create the modules and register them in the builder.
The same framework also gives you configuration free registration support. Just add an attribute to your services:
[Component]
public class MyService : IService
{
}
And run the builder extension method:
builder.RegisterAllComponents(Assembly.GetExecutingAssembly());
来源:https://stackoverflow.com/questions/10018831/autofac-module-scanning-for-various-applications