【问题标题】:Request Scoped Services in ASP.NET 5在 ASP.NET 5 中请求范围服务
【发布时间】:2015-04-14 16:06:42
【问题描述】:

我正在努力将服务范围限定为 ASP.NET 5 中的当前请求。我的启动代码如下所示:

public void ConfigureServices(IServiceCollection services)
{
  services.AddScoped<IMyService, MyService>();
}

public void Configure(IApplicationBuilder app)
{
  app.UseRequestServices();
  app.UseMiddleware<MyMiddleware>();
}

public class MyMiddleware
{
  RequestDelegate _next;
  IMyService MyService;

  public MyMiddleware(RequestDelegate next, IMyService myService)
  {
    _next = next;
    MyService = myService;
  }

  public async Task Invoke(HttpContext context)
  {
     --> Here - context.RequestServices does not contain myService
  }
}

传递给 MyMiddleware 构造函数的 IMyService 似乎不是请求范围的。它不是按请求处理的,并且在调用中间件时它没有在HttpContext.RequestServices 中注册。

好像我遗漏了一些明显的东西?

【问题讨论】:

    标签: c# asp.net asp.net-core


    【解决方案1】:

    好的,以更简单的形式写出代码后,我意识到了问题所在。

    中间件不是瞬态的/作用域的,所以作用域的依赖需要传递给 Invoke 方法,而不是中间件的构造函数。

    public class MyMiddleware
    {
      RequestDelegate _next;
    
      public MyMiddleware(RequestDelegate next)
      {
        _next = next;
      }
    
      public async Task Invoke(HttpContext context, IMyService myService)
      {
        --> Now working. MyService is registered on context.RequestServices 
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-28
      • 2019-04-26
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 2022-01-27
      相关资源
      最近更新 更多