c# - 使用 Autofac 注册以 Service 结尾的所有内容

标签 c# asp.net-mvc autofac convention-over-configur

所以我在 MVC 中使用 autofac,这样我的 Controller 就可以在构造函数上注入(inject)依赖项,我在我的 Global.asax 中有以下代码片段,它可以工作。

// Register your MVC controllers.
builder.RegisterControllers(typeof(MvcApplication).Assembly);

builder.RegisterType<PurchaseOrderSearchService>().As<IPurchaseOrderSearchService>().WithParameter("context", new PurchaseOrderManagerContext());

// Set the dependency resolver to be Autofac.
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

问题是我不想为我的所有服务一遍又一遍地执行 builder.RegisterType。那我该怎么做呢?

我觉得我想要的那种东西是

builder.RegisterAssemblyTypes(foo)
   .Where(t => t.Name.EndsWith("Services"))
   .WithParameter("context", new PurchaseOrderManagerContext());

但不知道 foo 应该是什么。或者,如果 RegisterAssemblyTypes 是正确的方法。 我知道按约定编码是解决方案,但不确定约定是什么。 我所有的服务都将以 int word Service 结尾,并且会有接口(interface)

所以 FooService 将有接口(interface) IFooService BarService 将有接口(interface) IBarService

还应该指出,所有服务都存在于名为 PurchaseOrderManager.Service 的类库中

最佳答案

您走在正确的轨道上。 “Foo”应该是包含要注册的类型的程序集 - 如果您使用的是单个程序集,那么以下应该有效:

builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly)
    .Where(t => t.Name.EndsWith("Services"))
    .WithParameter("context", new PurchaseOrderManagerContext())
    .AsImplementedInterfaces();

.AsImplementedInterfaces() 需要将它们注册为 IFooService - 没有它,它们只会被注册为 FooService 等。

如果您的类位于单独的程序集中,我通常建议您在该程序集中定义一个 autofac 模块:

public class ServiceModule : Module 
{
    protected override void Load(ContainerBuilder builder)
    {
        // "ThisAssembly" means "any types in the same assembly as the module"
        builder.RegisterAssemblyTypes(ThisAssembly)
            .Where(....
    }
}

然后在您的网络应用程序中注册:

builder.RegisterModule<PurchaseOrderManager.Service.ServiceModule>();

或者,使用我最初的建议,但明确指定包含服务的程序集:

builder.RegisterAssemblyTypes(typeof(PurchaseOrderManager.Service.FooService).Assembly)
    .Where(t => t.Name.EndsWith("Services"))
    .WithParameter("context", new PurchaseOrderManagerContext())
    .AsImplementedInterfaces();

您只需选择该程序集中存在的任何类。

关于c# - 使用 Autofac 注册以 Service 结尾的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37346564/

相关文章:

c# - 插入图片到Mysql出错

javascript - 如何处理一个表单上的两个提交按钮?

asp.net-mvc - AutoMapper.CreateMaps放置在哪里?

asp.net-mvc-3 - ASP.NET MVC 3 应用程序的扩展?

c# - 如何检测 EF 生成的多对多自引用关系中的引用循环?

c# - 尽管我们不能在 xaml 中应用它们,但是否有任何理由使用通用 View 模型?

javascript - FullCalendar 日期和时间呈现不正确

.net - Autofac 错误 : Could not load file or assembly 'System.Web.Http, Version=5.2.0.0,...' My project is Owin WebApi2 SelfHost

dependency-injection - 来自 Autofac 模块的 Net Core : access to appsettings. json 值

c# - 我可以在 Visual Studio 2015 中使用 Edge 加载 WebView 吗?