Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migration from ASP.NET Core's container to Autofac

I'm using ASP.NET Core and its builtin container. I want to migrate my registrations to Autofac.

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

There are more variations (e.g. delegates, IEnumerable<>), but these are the main ones.

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.

(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.)

like image 551
grokky Avatar asked Oct 29 '25 09:10

grokky


1 Answers

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.

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);
}
like image 186
Tseng Avatar answered Oct 31 '25 23:10

Tseng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!