DotNET Developer
DotNET Developer

Reputation: 9

Unable to resolve service for type 'Swashbuckle.AspNetCore.Swagger.ISwaggerProvider' only while Using Unity Dependency Injection

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'.
  1. Configured Unity in Program.cs:

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:

  1. .NET 8.0
  2. Swashbuckle.AspNetCore v7.2.0
  3. Unity v5.11.10
  4. Unity.Microsoft.DependencyInjection v5.11.5

Running locally using IIS Express.

Questions:

  1. Does Swashbuckle.AspNetCore have known issues when used with Unity as the DI container?
  2. Are there specific configurations or limitations when integrating Unity with ASP.NET Core's middleware pipeline?
  3. How can I ensure ISwaggerProvider is correctly resolved by SwaggerMiddleware when using Unity?

Any help or pointers on resolving this would be greatly appreciated!

Upvotes: 0

Views: 49

Answers (1)

Jason Pan
Jason Pan

Reputation: 21838

It's a known github issue.

Here is a workaround for this issue(.NET8).

if (false == unityContainer.IsRegistered<IServiceProviderIsService>())
{
    unityContainer.RegisterFactory<IServiceProviderIsService>(
        (IUnityContainer c) => null,
        new ContainerControlledLifetimeManager());
}

Upvotes: 0

Related Questions