ASP.NET 5 / MVC 6 中基于约定的绑定

Convention based binding in ASP.NET 5 / MVC 6

可以手动注册依赖:

services.AddTransient<IEmailService, EmailService>();
services.AddTransient<ISmsService, SmsService>();

当依赖太多时,手动注册所有依赖变得困难。

在 MVC 6 (beta 7) 中实现基于约定的绑定的最佳方法是什么?

P.S。在以前的项目中,我使用 Ninjectninject.extensions.conventions。但是我找不到 MVC 6 的 Ninject 适配器。

不,ASP.NET5内置DI库不支持批量注册。事实上,内置DI库中有many features that are needed to build large SOLID applications, but are not included

包含的 ASP.NET DI 库主要是为了扩展 ASP.NET 系统本身。对于您的应用程序,您最好使用其中一个成熟的 DI 库,并且 keep your configuration separate 来自用于配置 ASP.NET 系统本身的配置。 这消除了对适配器的需要。

存在 MVC 6 适配器,但由于 ASP.net 5 仍在候选版本中,它在 NuGet 上尚不可用,因此您需要添加 ASP.NET 5 "master" 从 MyGet 分支提要到您的 Visual Studio NuGet 包源。

此处提供了执行此操作的演练:

http://www.martinsteel.co.uk/blog/2015/using-ninject-with-mvc6/

如果有人仍然感兴趣。 这是我对 Autofac 问题的解决方案。它需要 AutofacAutofac.Extensions.DependencyInjection NuGet 包。

// At Startup:

using Autofac;
using Autofac.Extensions.DependencyInjection;

// ...

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    // Some middleware
    services.AddMvc();

    // Not-conventional "manual" bindings
    services.AddSingleton<IMySpecificService, SuperService>();

    var containerBuilder = new ContainerBuilder();
    containerBuilder.RegisterModule(new MyConventionModule());
    containerBuilder.Populate(services);
    var autofacContainer = containerBuilder.Build();

    return autofacContainer.Resolve<IServiceProvider>();
}

这是约定模块:

using Autofac;
using System.Reflection;
using Module = Autofac.Module;

// ...

public class MyConventionModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        var assemblies = new []
        {
            typeof(MyConventionModule).GetTypeInfo().Assembly,
            typeof(ISomeAssemblyMarker).GetTypeInfo().Assembly,
            typeof(ISomeOtherAssemblyMarker).GetTypeInfo().Assembly
        };

        builder.RegisterAssemblyTypes(assemblies)
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();
    }
}