使用Windsor Castle IoC来创建Windows服务

3
我正在编写 Active MQ 的 Windows 服务监听器。我尝试在项目中实现依赖注入,但不确定应该在哪里注册容器以及如何解决它?
我尝试将其放在 OnStart 方法中,但没有成功。
 protected override void OnStart(string[] args)
        {
            container = new WindsorContainer();
            //  IWindsorContainer container = new WindsorContainer();
            //container.Install(FromAssembly.This());
            container.Register(
                Component.For<IHttpClientProxyHandler>().ImplementedBy<HttpClientProxyHandlerWeb>().LifestyleTransient(),
                Component.For<IHttpClientProxy>().ImplementedBy<HttpClientProxyWeb>().LifestyleTransient(),
                //Component.For<IRedisCacheClient>().ImplementedBy<RedisCacheClient>().LifestyleTransient(),
                Component.For<IApplicationSettings>().ImplementedBy<ApplicationSettings>().LifeStyle.PerWebRequest,

                Component.For<ILogger>().ImplementedBy<Logger>().LifeStyle.PerWebRequest

            );


            this.messagingQueue = new ActiveMessagingQueue(new ApplicationSettings(), new Logger());
            this.logger = new Logger();
            this.applicationSettings = new ApplicationSettings();
            this.httpClientProxyHandler = container.Resolve<IHttpClientProxyHandler>();

            this.messagingQueue.OnMessageReceived += this.OnListenerMessage;
        }

我试图将其放在ServiceBase构造函数中 - 没有成功。甚至尝试将其放在主函数中。但是我一直在事件记录器中得到以下错误:

'Namespace.HttpClient.HttpClientProxyHandler'正在等待以下依赖项: - 未注册的服务'Castle.Windsor.IWindsorContainer'。

有人可以帮忙吗?


1
尝试使用IKernel替代IWindsorContainer。一般情况下,您不希望将容器/内核传递给实现... - Patrick Quirk
2个回答

2
我同意Patrick的观点,你不应该在已注册的组件中依赖于IWindsorContainer(或IKernel)。相反,要依赖于你需要的组件(或者更确切地说,这些组件实现的接口),确保它们也在容器中注册,并让Castle Windsor为你解决整个依赖层次结构。
为什么不应该为每个组件提供解析依赖项的机制?因为它隐藏了你的组件的实际依赖关系,并使得在测试中模拟/存根变得更加困难,因为你必须模拟服务定位器和实际依赖项。它还将依赖关系管理的责任推给了你;在Castle Windsor中,如果你明确地Resolve一个组件,最好在完成后也Release它。最后,它将你的组件与当前使用的特定依赖注入方式(即Castle Windsor)耦合在一起。

谢谢@Andy Lamb和Patrick。你们能否再详细解释一下,最好附上一些例子。 - PaRsH
@PaRsH 内核/容器是一种“服务定位器”,注入它是一种反模式。从这个问题/答案开始,如果需要更多信息,请进行额外的谷歌搜索。 - Patrick Quirk

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接