How to get instance of service in Windsor Castle

六眼飞鱼酱① 提交于 2020-01-17 07:24:25

问题


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

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?

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>();

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)?

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!

Code snippet would help a lot.

Thanks in advance!


回答1:


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).

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

See these related questions:

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



回答2:


Have a look at this article. It shows you how to write a static class that performs dependency resolution using Castle Windsor. You should consider putting this class in a separate project that can be referenced from both your UI and DAL projects to allow code reuse. As the article explains, your class should provide a bootstrapper facility that initializes your IoC container. In your case, this would look like:

public static class IoC
{
    private WindsorContainer _container;

    public static void Initialize()
    {
        _container = new WindsorContainer(
            new XmlInterpreter(new ConfigResource("castle"))
        );
    }
} 

The bootstrapper would be invoked from the application startup event in your UI projects Global.asax file.

The other methods for obtaining instances of objects from the container would be as per the article.



来源:https://stackoverflow.com/questions/1694778/how-to-get-instance-of-service-in-windsor-castle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!