0

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?

User101
  • 748
  • 2
  • 10
  • 29
  • 1
    `windsorContainer.ResolveAll` is not a registration... Please check out [MCVE] guidance and [edit] post with more complete example. (It looks like you expect all threads magically have context for a request which is obviously not the case, especially for threads that are not part of thread pool for handling requests) – Alexei Levenkov Apr 05 '19 at 22:47
  • @AlexeiLevenkov thanks, updated above – User101 Apr 06 '19 at 20:20

1 Answers1

0

You have a LifestylePerWebRequest() dependency in one of your IEventSubscribers. Check the full stack trace if you're unsure which one.

Krzysztof Kozmic
  • 27,267
  • 12
  • 73
  • 115