Reputation: 9
I am working on an ASP.NET Core
application and integrating Swagger with
Swashbuckle.AspNetCore
. My project uses Unity
as the dependency injection (DI) container instead of the default ASP.NET Core DI. However, I am encountering the following error when trying to load the Swagger UI or make any API calls:
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();
Problem Despite ISwaggerProvider being resolved successfully through Unity, the SwaggerMiddleware throws the error mentioned above when processing requests.
Environment:
Running locally using IIS Express.
Questions:
Swashbuckle.AspNetCore
have known issues when used with Unity
as the DI container?ISwaggerProvider
is correctly resolved by SwaggerMiddleware
when using Unity
?Any help or pointers on resolving this would be greatly appreciated!
Upvotes: 0
Views: 49
Reputation: 21838
Here is a workaround for this issue(.NET8).
if (false == unityContainer.IsRegistered<IServiceProviderIsService>())
{
unityContainer.RegisterFactory<IServiceProviderIsService>(
(IUnityContainer c) => null,
new ContainerControlledLifetimeManager());
}
Upvotes: 0