I have a custom middleware from which I want to add a scoped dependency.
public class MyMiddleware {
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext,
IOptionsSnapshot<ApiClientHttpSettings> settings,
IServiceCollection services)
{
services.AddScoped<ICustomer>(new Customer());
await _next(httpContext);
}
}
So that I can get it inside controllers:
public class CustomerController : ControllerBase
{
public ControllerBase(ICustomer customer)
{
}
}
But in the middleware IServiceCollection
cannot be resolved.
I want to do this because there is a lot of logic to resolve the DI involved.
I can also try to do inside ConfigureServices
but then I wont get access to IOptionsSnapshot<SupplyApiClientHttpSettings> settings
I need for every request.
Any pointer to right direction is really appreciated.
The answer was quite simple and close. Following is just what I had to do :
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICustomer>(provider => {
var settings = Configuration.GetSection("ApiClientHttpSettings").Get<ApiClientHttpSettings>();
return new Customer(settings.Name, settings.Age);
});
}
The above ticks all the boxes for me :