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

时间:2015-09-22 11:52:23

标签: c# dependency-injection ninject asp.net-core asp.net-core-mvc

可以手动注册依赖项:

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

如果依赖项太多,则很难手动注册所有依赖项。

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

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

3 个答案:

答案 0 :(得分:9)

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

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

答案 1 :(得分:2)

存在一个MVC 6适配器,但看到ASP.net 5仍处于Release候选版本中,它在NuGet上尚未可用,因此您需要添加ASP.NET 5&#34;主&#34;分支从MyGet转到Visual Studio NuGet包源。

可以在此处进行演练:

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

答案 2 :(得分:0)

如果某人仍然感兴趣的话。 这是我对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();
    }
}
相关问题