I am registering a type as below using Castle Windsor
container.Register(
Classes.FromAssemblyContaining(typeof(MyApplicationService))
.BasedOn(typeof(IEventSubscriber<>))
.WithService.AllInterfaces()
.LifestyleTransient());
container.Register(
Component.For<IEventHandlerResolver>()
.ImplementedBy<EventHandlerResolver>());
Events.EventHandlerResolver = container.Resolve<IEventHandlerResolver>();
The IEventHandlerResolver is implemented as below
public class EventHandlerResolver : IEventHandlerResolver
{
private readonly IWindsorContainer _windsorContainer;
public EventHandlerResolver(IWindsorContainer windsorContainer)
{
_windsorContainer = windsorContainer;
}
public IEnumerable<IEventSubscriber<T>> ResolveAll<T>() where T : IEvent
{
return _windsorContainer.ResolveAll<IEventSubscriber<T>>();
}
public void ReleaseAll(IEnumerable<object> instances)
{
if (instances == null)
{
throw new ArgumentNullException("instances");
}
foreach (var instance in instances)
{
_windsorContainer.Release(instance);
}
}
}
This works fine for a when raising an event on a normal http request. However I am then creating a background thread using HostingEnvironment.QueueBackgroundWorkItem
Any call to this type falls over on the background thread stating
System.InvalidOperationEception: 'HttpContext.Current is null. PerWebRequestLifestyle can only be used in ASP.Net'
This happens specifically on this line of code:
return _windsorContainer.ResolveAll<IEventSubscriber<T>>();
I have changed both registrations at the top to LifestylePerThread and LifestyleSingleton and LifestyleTransient, but none work. What am I missing?
Do background threads lose all Windsor registrations as they are on the current thread? Is there a recommended way of working with them and Castle Windsor?