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.