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

查看:209
本文介绍了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应用程序依赖于功能的,这意味着有时我会需要.InstancePerHtt prequest注册类型()其他层。不过,我也想有来自非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.

下面是一个<一个href=\"https://github.com/sogeti-se/Sogeti.Pattern/blob/master/source/Sogeti.Pattern/Sogeti.Pattern.Core.Autofac/BuilderExtensions.cs\"相对=nofollow>替代。

它使用 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
{
}

和运行商扩展方法:

builder.RegisterAllComponents(Assembly.GetExecutingAssembly());

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

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