ASP中基于约定的绑定.. Net 5 / MVC 6
本文关键字:Net 绑定 MVC 于约定 约定 ASP | 更新日期: 2023-09-27 18:13:59
可以手动注册依赖项:
services.AddTransient<IEmailService, EmailService>();
services.AddTransient<ISmsService, SmsService>();
当依赖项太多时,手动注册所有依赖项变得很困难。
在MVC 6 (beta 7)中实现基于约定的绑定的最佳方式是什么?注:在以前的项目中,我使用Ninject
和ninject.extensions.conventions
。但是我找不到MVC 6的Ninject适配器
不支持,在ASP中不支持批量注册。. NET 5内置DI库。事实上,构建大型SOLID应用程序所需要的许多特性并没有包含在内置的DI库中。
包含的ASP。. NET DI库主要用于扩展asp.net。NET系统本身。对于您的应用程序,最好使用成熟的DI库之一,并将您的配置与用于配置ASP的配置分开。NET系统本身。这样就不需要适配器了。
存在MVC 6适配器,但由于ASP.net 5仍处于候选发布阶段,因此它还不能在NuGet上使用,因此您需要添加ASP.net 6适配器。. NET 5 "master"分支从MyGet到你的Visual Studio NuGet包源。
可在此处获得此操作的演练:
http://www.martinsteel.co.uk/blog/2015/using-ninject-with-mvc6/如果有人仍然感兴趣的话。这是我对Autofac问题的解决方案。需要Autofac
和Autofac.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();
}
}