1

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 Answer 1

3

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.

1
  • Thank you , I defined another container and it worked. Jun 15, 2020 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.