Are Message Handlers outside the lifetime of a WebAPI request?
Well, as a matter of fact, they are. Unless you trigger the creation of the IDependencyScope
explicitly, the IDependencyScope
gets created (by calling request.GetDependencyScope()
) inside the DefaultHttpControllerActivator.Create
method.
To make sure your code runs within a dependency scope, all you have to do is call request.GetDependencyScope()
explicitly inside your handler:
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken) {
// trigger the creation of the scope.
request.GetDependencyScope();
Task<HttpResponseMessage> response;
var container = SimpleInjectorWebApiInitializer.container;
var rc = container.GetInstance<SimplePOCO>();
response = base.SendAsync(request, cancellationToken);
response.ContinueWith((responseMsg) => { });
return response;
}