适用于各种应用的 Autofac 模块扫描 [英] Autofac Module Scanning for Various Applications

查看:28
本文介绍了适用于各种应用的 Autofac 模块扫描的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您正在处理一个 ASP.NET MVC 项目,它是在一个解决方案中分成不同项目的层.每个项目都创建了 autofac 模块来连接依赖项.现在,我想扫描程序集并将所有模块注册到容器中.

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.

我采用了类似于此处共享的扩展方法http://goo.gl/VJEct

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);
  }
}

我的第一个问题是,考虑到这个样本是几年前提供的,这仍然是用于当前版本的 autofac 的可行构造吗?

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?

其次,MVC 应用程序依赖于其他层的功能,这意味着有时我需要使用 .InstancePerHttpRequest() 注册类型.但是,我还希望可以选择从非 Web 应用程序中引用它们,而不是依赖 System.Web.注册可在这些不同上下文中使用的模块的最佳方法是什么?

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?

推荐答案

我不会在容器中注册模块.我认为没有理由这样做.

I would not register the modules in the container. I see no reason to do that.

这是一个 替代.

它使用 Activator.CreateInstance 来创建模块并在构建器中注册它们.

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());

这篇关于适用于各种应用的 Autofac 模块扫描的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆