在ASP.NET 5中请求范围内的服务

时间:2015-02-13 15:10:19

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

我很难将服务范围限定为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中注册。

好像我错过了一些明显的东西?

1 个答案:

答案 0 :(得分:4)

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

中间件不是临时/范围的,因此需要在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 
  }
}