Autofac Module Scanning for Various Applications

大城市里の小女人 提交于 2019-12-23 17:47:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!