How or is it possible to use SimpleInjector with ASP.NET Core 6 Minimal APIs
Hi,
After poking about with minimal APIs with the view to move some of our older, basic WCF services to minimal APIs, I've not been able to find any information about wiring up Simple Injector with it.
Most of the Simple Injector integrations seem to be able to hook into the underlying library's call to get instances resolved using Simple Injector, but it's unclear to me if Minimal APIs has similar hooks.
Is it currently possible to get Minimal APIs integrated with Simple Injector or does one of the other integration methods - eg AddControllerActivation() - actually hook into the same resolution process that Minimal APIs use?
I haven't found a way to intercept the creation of intercepting the creation of creating dependencies injected into Minimal API maps. As far as I can see, resolving services is hard-coded to the built-in DI abstraction.
See: https://github.com/dotnet/aspnetcore/issues/41863
Microsoft confirmed that an integration point is missing in .NET 6. The workaround is to create a wrapper class that allows forwarding resolving the type to Simple Injector.
This is the wrapper:
public sealed class Service<T> where T : class
{
public readonly T Instance;
public Service(SimpleInjector.Container container) => this.Instance = container.GetInstance<T>();
}
Here's how to wrap your services in the Service<T> wrapper:
app.MapGet("/{id}", (int id, int page, Service<IRepository> repository) =>
{
return repository.Instance.GetAll();
});
This is how to wire things:
// Import the SimpleInjector and SimpleInjector.Integration.AspNetCore NuGet packages
using SimpleInjector;
var builder = WebApplication.CreateBuilder(args);
var container = new Container();
builder.Services.AddSimpleInjector(container, options =>
{
options.AddAspNetCore();
});
builder.Services.AddTransient(typeof(Service<>), typeof(Service<>));
// Register Simple Injector dependencies here
container.Register<IRepository, FakeRepository>();
var app = builder.Build();
app.Services.UseSimpleInjector(container);
app.MapGet("/{id}", (int id, int page, Service<IRepository> repository) =>
{
return repository.Instance.GetAll();
});
app.Run();
Apologies for taking a while to respond as I wanted to follow the whole conversation and haven't had the time to try things out for myself.
This is a fairly straight-forward and suitable workaround.
Thank you very much for your time and effort put into coming up with a solution as well as advocating for better DI hooks and practices!