Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Autofac DI in a WebAPI messageHandler?

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?

like image 551
Eilistraee Avatar asked Sep 26 '12 20:09

Eilistraee


1 Answers

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);
    }
}
like image 119
nemesv Avatar answered Oct 12 '22 20:10

nemesv