Gerino
Gerino

Reputation: 1983

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:

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.

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?

If you could provide me with a sample of correct, best-practices style basic DelegatingHandler using Autofac-resolved service, that would help me greatly.

Upvotes: 0

Views: 304

Answers (1)

Travis Illig
Travis Illig

Reputation: 23934

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. Of course, make sure the Autofac middleware executes before your middleware so the scope can be created for you; and if that's the case, it'll clean up after you, too. Automatically.

Upvotes: 1

Related Questions