如何在温莎城堡获得服务实例 [英] How to get instance of service in Windsor Castle

查看:63
本文介绍了如何在温莎城堡获得服务实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多层应用程序(ASP MVC:UI项目,DAL项目)中,我在web.config中注册了组件。

In a multilayer application (ASP MVC: UI project, DAL project) i registered in web.config the components.

现在我有这个问题:工作单元模式已经实现,我需要获取特定服务的当前实例。服务的注册发生在UI项目中,但是我需要在DAL项目中获取此服务的当前实例。我如何获得此参考?

Now i have this problem: Unit of Work pattern has do be implemented and i need to get the current instance of a particular service. The registration of the services happened in the UI project, but i need to get the current instance of this service in the DAL project. How do i get this reference?

在UI项目中,我已经需要一种解决问题的方法:

In the UI project i already needed a way to get something resolved:

container = new WindsorContainer(
                new XmlInterpreter(new ConfigResource("castle"))
            );
            personRepository= container.Resolve<IPersonRepository>();

在DAL项目中使用相同的技术是否可以?如果是,我是否应该将配置写在一个单独的文件中,以便所有层(项目)都可以访问它?

Would it be OK to use the same technique in the DAL project? If yes, should i write the configuration in a separate file, so that it can be accessed by all the layers(projects)?

抱歉(我认为)是幼稚的问题,但这是我使用Castle的第一个项目,我想我不了解它的全局图片!

Sorry for this (i think) naive question but it's my first project using Castle and i think i don't understand the big picture of it!

代码段会很有帮助。

预先感谢!

推荐答案

简而言之:每个应用程序一个容器实例,一个容器配置具有应用程序所需的所有组件。如果您的DAL中需要服务,请通过构造函数(如果依赖项为必需)或setter(如果依赖项为可选)在DAL类中注入适当的服务接口。

In a nutshell: one container instance per application, one container configuration that has all the components you need for the application. If you need a service in your DAL, inject the appropriate service interface in your DAL class via constructor (if the dependency is required) or setter (if the dependency is optional).

尽力避免使用静态IoC网关,它隐藏了组件的真正依赖关系,并妨碍了可测试性。

Try really hard to avoid using a static IoC gateway, it hides the true dependencies of a component and it hampers testability.

请参阅以下相关问题:

  • Usage of IoC Containers; specifically Windsor
  • Is it correct to have many Castle Windsor containers per application if those containers belong to different tiers?

这篇关于如何在温莎城堡获得服务实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆