简体   繁体   English

使用QueueBackgroundWorkItem运行后台线程时,Castle Windsor问题

[英]Castle Windsor issue when running background thread with QueueBackgroundWorkItem

I am registering a type as below using Castle Windsor 我正在使用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 IEventHandlerResolver实现如下

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. 这适用于在正常的http请求上引发事件时。 However I am then creating a background thread using HostingEnvironment.QueueBackgroundWorkItem 但是,然后我使用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. 我已将顶部的注册更改为LifestylePerThread和LifestyleSingleton以及LifestyleTransient,但均无效。 What am I missing? 我错过了什么?

Do background threads lose all Windsor registrations as they are on the current thread? 背景线程是否会丢失所有Windsor注册,因为它们在当前线程上? Is there a recommended way of working with them and Castle Windsor? 是否有推荐的方式与他们和温莎城堡一起工作?

You have a LifestylePerWebRequest() dependency in one of your IEventSubscriber s. 您在其中一个IEventSubscriber有一个LifestylePerWebRequest()依赖IEventSubscriber Check the full stack trace if you're unsure which one. 如果您不确定哪一个,请检查完整的堆栈跟踪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM