13

I successfully wired Autofac in my ASP.NET WebAPI project, and now I am wondering how to be able to resolve services in my MessageHandlers.

As MessageHandlers have to be added at application startup, it's clear that I won't be able to resolve them in a request lifetime scope. No problem here.

However, I would like to find a way to get the current request lifetime scope during the execution of the SendAsync method of the MessageHandler, in order to be able to (for instance) perform token verification, logging in a repository, etc...

How should I do that?

Eilistraee
  • 8,220
  • 1
  • 27
  • 30

1 Answers1

23

You can use the GetDependencyScope() extension method on the HttpRequestMessage which gives you an IDependencyScope from where you can resolve any service that you want in you handler:

public class MyHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, 
        CancellationToken cancellationToken)
    {
        IMyService myservice =
         (IMyService)request.GetDependencyScope().GetService(typeof(IMyService));
        // Do my stuff with myservice
        return base.SendAsync(request, cancellationToken);
    }
}
MobileOverlord
  • 4,580
  • 3
  • 22
  • 30
nemesv
  • 138,284
  • 16
  • 416
  • 359
  • Thank you. It was as simple as that... -_-' I almost feel shame. – Eilistraee Sep 28 '12 at 13:27
  • Still, I wouldn't want to use the resolver in the message handler directory. Instead, I would register a factory that can turn an HttpRequestMessage into the desired service and inject that into the contructor of the handler. – Dave Van den Eynde Apr 13 '15 at 13:05