我正在使用 ASP.NET Core 及其内置容器。我想将我的注册迁移到 Autofac。
The Autifac 文档 http://autofac.readthedocs.io/en/latest/integration/aspnetcore.html没有“迁移指南”,所以我想确保我做的事情是正确的。
ASP.NET Core container -> Autofac
---------------------- -------
// the 3 big ones
services.AddSingleton<IFoo, Foo>() -> builder.RegisterType<Foo>().As<IFoo>().SingleInstance()
services.AddScoped<IFoo, Foo>() -> builder.RegisterType<Foo>().As<IFoo>().InstancePerLifetimeScope()
services.AddTransient<IFoo, Foo>() -> builder.RegisterType<Foo>().As<IFoo>().InstancePerDependency()
// default
services.AddTransient<IFoo, Foo>() -> builder.RegisterType<Foo>().As<IFoo>()
// multiple
services.AddX<IFoo1, Foo>();
services.AddX<IFoo2, Foo>(); -> builder.RegisterType<Foo>().As<IFoo1>().As<IFoo2>().X()
// without interface
services.AddX<Foo>() -> builder.RegisterType<Foo>().AsSelf().X()
还有更多的变化(例如代表,IEnumerable<>
),但这些是主要的。
它是否正确?我是否在某个地方遗漏了一些细微差别,因为 Autofac 相当复杂。
UPDATE
到目前为止,评论都是“但是为什么”,但这并不重要(尽管我已经在其中一些评论中解释了我们的推理)。这是一个合理的问题。如果您对这两个容器都有使用经验,我非常感谢您的意见。
(作为这些解释的简短总结 - 根据我们多年的经验,我们经历了惨痛的教训,提供两种方法来做同一件事从来都不是一个好主意,因为它会增加 100% 的失败几率。所以选择一种方法并坚持下去。一年后,一些初级开发人员会因为对其他选择感到困惑而搞砸一些东西。)
您应该使用.AddXxx
方法来自Microsoft.Extensions.DependencyInjection
注册它并通过IServiceCollection
到 autofac。
这使得在容器之间进行更改变得更加容易。
当然,如果您需要 Autofac/3rd party IoC 容器的某些功能(自动发现等),那么您需要使用容器本机方法。
private readonly IContainer container;
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// your normal registrations
services.AddSingleton<IMySingleton,MySingleton>();
var builder = new ContainerBuilder();
builder.Populate(services);
// build container
container = builder.Build();
// and return it
return new AutofacServiceProvider(container);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)