我正在练习了解更多关于ASP.NET Core中的依赖注入和中间件的信息,我遇到了一个无法解决的问题,因此需要StackOverflow的其他成员的帮助。
在我的项目中,我试图创建一个中间件,它将把一些初始数据与运行时收集的另一个数据结合起来。
我有以下类作为初始数据
public class A
{
public string Name { get; set; }
public string Description { get; set; }
}
我为依赖项注入创建了以下类
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);
}
}
}
在
Startup.cs
文件,我将其注入如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddInitialData(d =>
{
d.Name = "Some name";
d.Description = "Some description";
});
}
我还写了我的中间件如下:
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
this._next = next;
}
public async Task Invoke(HttpContext context)
{
await this._next(context);
}
}
并在
Starup.cs
文件如下:
public void Configure(IApplicationBuilder app, IHostEnvironment env)
{
app.UseMiddleware(typeof(MyMiddleware));
}
此时,我需要访问从A类实例化的对象,并在
Invoke(HttpContext context)
方法。
到目前为止,我已经发现了一些以不同方式使用依赖注入的例子,例如将对象(从类a)传递给中间件的构造函数,但我希望在编写对象时读取其值设置的对象。