c# - 从自定义中间件访问ConfigureServices中注入(inject)的参数

标签 c# .net-core dependency-injection middleware

我正在练习了解有关 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/

相关文章:

c# - 防止 Simple.OData.Client 获取整个结构

javascript - 如何在开发者控制台中使用 Chrome 注入(inject) jQuery?

c# - 从另一个命令 Handle() 方法中调用命令

c# - CreateProcessWithTokenW - C# 中的用法示例

c# - 在 Owin、Katana 和 Nancy 中成功进行 cookie 身份验证后重定向到 ReturnUrl

设置为 NULL 的 C# Marshall void*

asp.net-mvc-3 - 工作单元和存储库模式是一起使用还是两个解决方案?

c# - 在 ASP.NET Core 中使用 ADO.NET 作为数据访问层

c# - 无法在 Razor 页面上使用 <component/> 标签助手?

asp.net-core - .NET Core 1.0 VSTest 的 VSTS 版本警告 : No test is available