Search code examples
c#asp.net-coredependency-injection.net-coremiddleware

How to pass dependencies into a controller from a custom middleware?


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.


Solution

  • 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 :

    1. New instance for each request
    2. Able to read updated config at the time of request
    3. Create instance according to custom logic