Search code examples
c#.netasp.net-coredependency-injectionautofac

Is there a way to use Autofac Service Registration With Microsoft DI


I have some legacy projects that use Autofac for their DI container and they have all of their registration nicely organized into Modules. I have a new .net 8 API project and some flows need to reference these legacy projects. Rather than re-register all of my legacy dependencies, is there a way to use the already created Modules and register those with my IServiceCollection? Ive been looking over Autofac's documentation and the only thing I see is using Microsoft's registration with Autofac, where Autofac becomes the main container. I would like to keep Microsoft as my main container, but just use Autofac for registering old services. The only thing I saw that looked like it might do what I want was with the Autofac.Extensions.DependencyInjection package where I tried:

services.AddAutofac(builder => builder 
{
    builder.AddModule(new LegacyModule);
});

but it looks like AddAutofac is deprecated and didn't work how I expected anyway.


Solution

  • Following code works to register autofac module to default Webapplicationbuilder. Assume you have this module:

        public class Student
        {
            public string Name { get; set; } = "Tom";
        }
    
        public class MyAutofacModule : Module
        {
            protected override void Load(ContainerBuilder builder)
            {
                builder.RegisterType<Student>();
            }
        }
    

    Then you could add to webapi like

    builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
    
    builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
    {
        containerBuilder.RegisterModule(new MyAutofacModule());
    });
    

    Package Autofac.Extensions.DependencyInjection

    -------Below is startup pattern-----

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    

    Startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            ...
        }
    
        // ConfigureContainer is where you can register things directly with Autofac.
        public void ConfigureContainer(ContainerBuilder builder)
        {
            // Register your Autofac modules or registrations here
            builder.RegisterModule(new MyAutofacModule());
        }