我正在练习了解有关 ASP.NET Core 中的依赖注入(inject)和中间件的更多信息,但我遇到了一个无法解决的问题,因此需要 StackOverflow 的其他成员的帮助。
在我的项目中,我试图创建一个中间件,它将一些初始数据与运行时收集的其他数据结合起来。
我有以下类作为初始数据
public class A
{
public string Name { get; set; }
public string Description { get; set; }
}
我创建了以下类用于依赖注入(inject)
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
文件中,我将其注入(inject)如下:
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)
方法时注入(inject)到应用程序中的对象。
到目前为止,我发现了一些以不同方式使用依赖注入(inject)的示例,例如将对象(从类 A)传递给中间件的构造函数,但我想读取对象及其写入时设置的值.
最佳答案
由于您已在启动时注册了 A
实例,因此您可以将其添加到中间件构造函数中的签名中:
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);
}
关于c# - 从自定义中间件访问ConfigureServices中注入(inject)的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72141621/