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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With