hcp*_*hcp 6 c# dependency-injection ninject asp.net-core-mvc asp.net-core
可以手动注册依赖项:
services.AddTransient<IEmailService, EmailService>();
services.AddTransient<ISmsService, SmsService>();
Run Code Online (Sandbox Code Playgroud)
当依赖关系太多时,手动注册所有依赖项变得很困难.
在MVC 6(beta 7)中实现基于约定的绑定的最佳方法是什么?
PS在我以前使用的项目Ninject
有ninject.extensions.conventions
.但我找不到适用于MVC 6的Ninject适配器.
不,ASP.NET 5内置DI库中不支持批量注册.事实上,构建大型SOLID应用程序需要许多功能,但不包含在内置DI库中.
包含的ASP.NET DI库主要用于扩展ASP.NET系统本身.对于您的应用程序,最好使用其中一个成熟的DI库,并将配置与用于配置ASP.NET系统本身的配置分开.这消除了对适配器的需求.
如果对某人来说仍然有趣的话。这是我对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>();
}
Run Code Online (Sandbox Code Playgroud)
这是约定模块:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
534 次 |
最近记录: |