How do I get the current Castle Windsor container?

给你一囗甜甜゛ 提交于 2019-12-01 03:15:30

There are many ways to solve this problem but I think the most common is to create a singleton helper class to hold the reference. Keep in mind you want to app to use DI to get everything from the container automatically. Perhaps only a few calls from the app will be to the container. Look at the controller factories for Windsor.

Something like this...

public static class ContainerManager
{
    public static IWindsorContainer Container = null;
}

Now I have been known to take it a step further and you could include some utilities with a get...

    public static class ContainerManager
    {
        private static IWindsorContainer _container = null;
        public static IWindsorContainer Container
        {
             get {
                 if (_container == null) {
                      // run installers, set _container = new container
                 }
                 return _container;
             }

        }
    }

I also realize you might be asking how do I get the container from a downstream dependent object... you can register the container with its self. By default it will register IKernel, but you can register IWindsorContainer for injection later. I would highly discourage using the container directly. As in you code above... do you do a Release when you are done???

There is interface in Windsor for this purpose. It is called IContainerAccessor. Best place to implement it is the Global.asax file:

public class WebApplication : HttpApplication, IContainerAccessor {
  static IWindsorContainer container;

  public IWindsorContainer Container {
    get { return container; }
  }

  protected void Application_Start() {
    var bootstrapper = new WindsorConfigTask();
    bootstrapper.Execute();
    container = bootstrapper.Container; 
  }

  protected void Application_End() {
    container.Dispose();
  }
}

The usage in your web form is as following:

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