Search code examples
c#.net-coredependency-injectionmiddleware

Accessing the parameters injected in ConfigureServices from custom Middleware


I am practicing to learn more about the Dependency Injection and the Middleware in ASP.NET Core and I have faced an issue I can not resolve, so need the assistance of fellow members of StackOverflow.

In my project I am trying to create a middleware which will combine some initial data with another data gathered in the runtime.

I have the following class as the initial data

public class A
{
    public string Name { get; set; }
    public string Description { get; set; }
}

I created the following class for dependency injection

namespace Microsoft.Extensions.DependencyInjection
{
    public static class MiddlewareInitialDataExtension
    {
        public static IServiceCollection AddInitialData(this IServiceCollection services, Action<A> data)
        {
            A a = new A();
            data(a);
            return services.AddSingleton<A>(a);
        }    
    }
}

And in the Startup.cs file I am injecting it as follows :

public void ConfigureServices(IServiceCollection services)
{
    services.AddInitialData(d =>
    {
        d.Name = "Some name";
        d.Description = "Some description";
    });
}

I have also written my Middleware as follows :

public class MyMiddleware
{
    private readonly RequestDelegate _next;

    public MyMiddleware(RequestDelegate next)
    {
        this._next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        await this._next(context);
    }
}

and registered my middleware in the Starup.cs file as follows :

public void Configure(IApplicationBuilder app, IHostEnvironment env)
{
    app.UseMiddleware(typeof(MyMiddleware));
}

At this point I need to access the object instantiated from the A class and injected into the app when Invoke(HttpContext context) method is called.

So far I have found some examples using dependency injection in a different way such as passing the object (from class A) to the constructor of middleware, but instead I would like to read the object with its values set as it is written.


Solution

  • As you've registered the instance of A in startup, you can add that to the signature in your middleware constructor:

    private readonly A _a;
    
    public MyMiddleware(RequestDelegate next, A instanceOfA)
    {
      _a = instanceOfA;
    }
    
    public async Task Invoke(HttpContext context)
    {
        Console.WriteLine(_a.Name); // should print "Some name"
        await this._next(context);
    }