简体   繁体   English

在WebApi2中使用Autofac范围

[英]Using Autofac scopes in WebApi2

I have went through most of the documentation, and I am still unsure about specific usage of dependency scopes. 我已经阅读了大多数文档,但仍不确定依赖范围的具体用法。

When my request hits my controller, I usually can use dependencies of the controller (provided via Constructor Injection) and not worry myself about it much. 当我的请求到达我的控制器时,我通常可以使用控制器的依赖项(通过构造函数注入提供),而不必为它担心。

However, I am writing a Delegating Handler : 但是,我正在编写Delegating Handler

public class MyHandler: DelegatingHandler
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        // I need IMyService here
        return await base.SendAsync(request, cancellationToken);
    }

I initially tried doing: 我最初尝试做的是:

using(var scope = request.GetDependencyScope()){
    var service = scope.GetService(typeof(IMyService));
}

But that - while it works - seems to close the scope and prevent my Controller from even initializing correctly. 但是,尽管它起作用了,但似乎关闭了作用域,甚至阻止了我的Controller正确初始化。

I could do: 我可以做:

{
      var requestScope = request.GetDependencyScope();
      var scope = requestScope.GetRequestLifetimeScope();

      var service = scope.Resolve<IMyService>();
      // use service
      return await base.SendAsync(request, cancellationToken);
}

but will that not create resource leak? 但这不会造成资源泄漏吗? Will the RequestLifetimeScope be disposed of when the request finishes? 请求完成后会否处理RequestLifetimeScope

If you could provide me with a sample of correct, best-practices style basic DelegatingHandler using Autofac-resolved service, that would help me greatly. 如果您可以使用Autofac解析的服务为我提供正确的,最佳实践样式的基本DelegatingHandler示例,那将对我有很大帮助。

The request-level dependency scope is created for you and disposed for you. 请求级别的依赖关系范围是为您创建并为您分配的。 Just get it (not inside a using ) and resolve from it if you need to. 只需获取它(不在using ),然后根据需要从中解决。 Of course, make sure the Autofac middleware executes before your middleware so the scope can be created for you; 当然,请确保您的中间件之前执行Autofac中间件以便可以为您创建范围。 and if that's the case, it'll clean up after you , too. 如果是这种情况,它也会在您之后进行清理。 Automatically. 自动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM