本文介绍了'不支持返回System.IServiceProvider的ConfigureServices.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在ASP核心3.0中使用此AutoFac
I need ti use this AutoFac
in ASP core 3.0
当我在启动时使用此代码时:
When I use this code in startu up:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddControllers();
return services.BuildAutofacServiceProvider();
}
它向我显示此错误:
然后我通过以下方式更改program.cs:
And I change the program.cs by this:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
但是没有解决.
这是BuildAutofacServiceProvider()
代码:
public static IServiceProvider BuildAutofacServiceProvider(this IServiceCollection services)
{
var ContainerBuilder = new ContainerBuilder();
ContainerBuilder.Populate(services);
ContainerBuilder.AddService();
var container = ContainerBuilder.Build();
return new AutofacServiceProvider(container);
}
我该如何解决这个问题?
How can I solve this problem?
推荐答案
为ASP.NET Core 3.0+配置Autofac的启动语法已更改
Startup syntax has changed for configuring Autofac for ASP.NET Core 3.0+
除了在主机生成器上使用以下内容
In addition to using the following on the host builder
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
在Startup
中执行以下格式
public void ConfigureServices(IServiceCollection services) {
//... normal registration here
// Add services to the collection. Don't build or return
// any IServiceProvider or the ConfigureContainer method
// won't get called.
services.AddControllers();
}
// ConfigureContainer is where you can register things directly
// with Autofac. This runs after ConfigureServices so the things
// here will override registrations made in ConfigureServices.
// Don't build the container; that gets done for you. If you
// need a reference to the container, you need to use the
// "Without ConfigureContainer" mechanism shown later.
public void ConfigureContainer(ContainerBuilder builder) {
// Register your own things directly with Autofac
builder.AddMyCustomService();
//...
}
参考 ASP.NET Core 3.0+的> Autofac文档
这篇关于'不支持返回System.IServiceProvider的ConfigureServices.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!