我正在开发一个
ASP.NET Core
应用程序并将 Swagger 与
Swashbuckle.AspNetCore
。我的项目使用 Unity
作为依赖注入 (DI) 容器,而不是默认的 ASP.NET Core DI。但是,在尝试加载 Swagger UI 或进行任何 API 调用时遇到以下错误:
Unable to resolve service for type 'Swashbuckle.AspNetCore.Swagger.ISwaggerProvider' while attempting to Invoke middleware 'Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware'.
var builder = WebApplication.CreateBuilder(args);
var unityContainer = new UnityContainer();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddControllers().AddControllersAsServices();
builder.Services.AddControllersWithViews(); // Registers MVC services, including Razor view engine
UnityConfig.RegisterTypes(unityContainer); //Registers services like below for example
//container.RegisterType<DataContextFactory>();
builder.Host.UseUnityServiceProvider(unityContainer); //If this line removed, it Swagger loads
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapControllers(); // Enable routing to controllers
app.Run();
问题 尽管通过Unity成功解析了ISwaggerProvider,但SwaggerMiddleware在处理请求时会抛出上述错误。
环境:
使用 IIS Express 在本地运行。
问题:
Swashbuckle.AspNetCore
一起用作 DI 容器时,Unity
是否存在已知问题?ISwaggerProvider
时如何确保 SwaggerMiddleware
被 Unity
正确解析?任何有关解决此问题的帮助或指示将不胜感激!
这是此问题的解决方法(.NET8)。
if (false == unityContainer.IsRegistered<IServiceProviderIsService>())
{
unityContainer.RegisterFactory<IServiceProviderIsService>(
(IUnityContainer c) => null,
new ContainerControlledLifetimeManager());
}