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

可以手动注册依赖项:

services.AddTransient(); services.AddTransient(); 

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

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

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

不,ASP.NET 5内置DI库中不支持批量注册。 事实上, 构建大型SOLID应用程序需要许多function,但不包含在内置DI库中。

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

存在一个MVC 6适配器,但看到ASP.net 5仍在Release候选版本中,它在NuGet上尚不可用,因此您需要将MyGet中的ASP.NET 5“master”分支源添加到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(); var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterModule(new MyConventionModule()); containerBuilder.Populate(services); var autofacContainer = containerBuilder.Build(); return autofacContainer.Resolve(); } 

这是约定模块:

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