0
votes

I want to use autofac injection instead of default .net core solution.

Here is my startup file :

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc(option => option.EnableEndpointRouting = false) ;
           

    var cb = new ContainerBuilder();
    cb.RegisterModule<mydependecymodule>();
    cb.Populate(services);
    var container = cb.Build();

    return new AutofacServiceProvider(container);
}


// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)                           
{
    app.UseDeveloperExceptionPage();
    app.UseStatusCodePages();
    app.UseStaticFiles();
         
    app.UseMvc(routes=>routes.MapRoute("default","/{controller=home}/{action=index}"));
}

And here is my program.cs

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

But when I run my application I get this error in my main method:

System.NotSupportedException: 'ConfigureServices returning an System.IServiceProvider isn't supported.'

1

1 Answers

2
votes

In ASP.NET Core 3.0 the ASP.NET Core hosting model changed and you can't return an IServiceProvider anymore. This is documented in the Autofac docs for integrating with ASP.NET Core 3.0+.

You have to switch your ConfigureServices to be void, and if you want to register stuff directly with Autofac you need to use ConfigureContainer. You also need to register the AutofacServiceProviderFactory in your Program.Main method when you construct the host. There are examples in the documentation showing how to do this.