I am using Castle Windsor for a DI container for Web API 2 and some of my controllers have EF DbContext dependencies, which I am injecting using the following CW installers (this part works fine):
public class ApiControllerInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Classes.FromThisAssembly().BasedOn<ApiController>().LifestylePerWebRequest());
}
}
public class MyEntitiesInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Component.For<MyEntities>().LifestylePerWebRequest());
}
}
I also have global logging in place with the following message handler:
public class LoggingHandler : DelegatingHandler
{
private readonly IWindsorContainer _container;
public LoggingHandler(IWindsorContainer container)
{
_container = container;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
// Logic here to parse the request, send off the request, and then parse the response for logging info
// Log to database
using (MyEntities myEntities = _container.Resolve<MyEntities>())
{
// Log to database using MyEntities (DbContext)
}
return response;
}
}
... which gets set in WebApiConfig.cs like this:
public static void Register(HttpConfiguration config, IWindsorContainer container)
{
// Unrelated code
config.MessageHandlers.Add(new LoggingHandler(container));
}
The problem is that I get an exception in the LoggingHandler
when trying to access MyEntities
(which extends EF DbContext
) because it says it has already been disposed. I think that this happens because the MyEntitiesInstaller
registers it as LifestylePerWebRequest()
and by this point the request has already completed. I don't think it's a good idea to globally change the lifestyle of the DbContext
because for api controller purposes we do want it to be an instance per web request. But how do I prevent it from being disposed before the logging happens (or even better, use a separate instance for the logging)?