I currently work in a asp.net MVC Web Api project using castle 3.1.
I registered a component with a lifestyle 'PerWebRequest'.
I would like to manually tell castle which instance to use instead of letting the container create the instance. On each web request.
Here's how I achieve this:
I cache the HttpRequestMessage instance in the HttpContext's Items collection via a DelegatingHandler(for those who don't know, DelegatingHandler are first extension point offered by the WebApi framework). When registering my component, I use a factory and retrieve the HttpRequestMessage from the context.
Here's the code:
public class InjectingCurrentHttpRequestHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpContext.Current.AddHttpRequest(request);
var output = base.SendAsync(request, cancellationToken);
HttpContext.Current.RemoveHttpRequest();
return output;
}
}
Here's how I register my component:
container.Register(Component.For<HttpRequestMessage>()
.LifestylePerWebRequest()
.UsingFactoryMethod(() =>
{
var context = HttpContext.Current;
if (context == null)
throw new Exception("HttpContext is null. Resolving HttpRequestMessage can only be done during an http request. Have you forgot to add the '" + typeof(InjectingCurrentHttpRequestHandler).Name + "' handler in the framework?");
return context.GetHttpRequest();
}));
It does work but I would like to avoid using the HttpContext.Current instance. Is there a better way to achieve this using castle?
I feel like the support for this should be built-in castle, but can't find it.
Thank you,