我正在使用ASP.NET Core及其内置容器.我想将我的注册迁移到Autofac.
I'm using ASP.NET Core and its builtin container. I want to migrate my registrations to Autofac.
Autifac文档没有迁移指南",所以我想确保自己做的正确.
The Autifac docs don't have a "migration guide", so I want to be sure I'm doing things correctly.
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<>),但这是主要的变化形式.
There are more variations (e.g. delegates, IEnumerable<>), but these are the main ones.
这是正确的吗?我是否在某个地方缺少细微差别,因为Autofac非常复杂.
Is this correct? Am I missing some nuance somewhere, because Autofac is quite complex.
更新 到目前为止,评论都是但是为什么"的变化,但这并不重要(尽管我已经在其中一些评论中解释了我们的推理).这是一个合理的问题. 如果您对这两个容器都有经验,我将非常感谢您的投入.
UPDATE Comments so far are of the "but why" variety, but that doesn't matter (though I've explained our reasoning in some of those comments). This is a legitimate question. If you have experience with both containers, I'd really appreciate your input.
(作为这些解释的简短摘要-在我们多年的经验中,我们已经学会了很难的方法,即提供两种方法来做同一件事绝不是一个好主意,因为这样做会使失败的几率增加100 %,所以选择一种方法并坚持下去.一年后的今天,一些初级开发人员会因为某种替代方案而感到困惑,从而炸毁了某些东西.)
(As a short summary of those explanations - in our many years of experience, we've learned the hard way that providing two ways to do the same thing is never a good idea, because it increases your odds of failure by 100%. So choose one way and stick to it. A year from now some junior dev will blow something up because he gets confused by the alternatives.)
推荐答案您应该使用Microsoft.Extensions.DependencyInjection中的.AddXxx方法进行注册,并将IServiceCollection传递给autofac.
You should use the .AddXxx methods from Microsoft.Extensions.DependencyInjection to register it and pass the IServiceCollection to autofac.
这使得在容器之间进行更改变得更加容易.
This makes it easier to change between containers.
当然,如果您需要Autofac/第三方IoC容器的某些功能(自动发现等),则需要使用容器的本机方法.
Of course, if you need certain features of Autofac/3rd party IoC container (autodiscovery etc), then you need to use the containers native methods.
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); }更多推荐
从ASP.NET Core的容器迁移到Autofac
发布评论