开发者

Castle Windsor lifecycle

开发者 https://www.devze.com 2022-12-08 19:52 出处:网络
Currently, I\'m trying to use the WindsorCont开发者_StackOverflow社区ainer as a mean to get rid of Singletons in my program. After some testing, I realised, that I need a way to keep the WindsorContai

Currently, I'm trying to use the WindsorCont开发者_StackOverflow社区ainer as a mean to get rid of Singletons in my program. After some testing, I realised, that I need a way to keep the WindsorContainer throughout my program, but how? The documentation isn't that good. Could anybody give me an example of a way to use Castle Windsor to create a useable Container throughout my whole program.


Create a static class that holds the container instance:

public static class IoC
{
     private static IContainer innerContainer;

     public static void Initialize(IContainer container)
     {
          innerContainer = container;
     }

     public static T Resolve<T>()
     {
          return innerContainer.Resolve<T>();
     }

     // wrap more container methods here
}

In your main method (or global.asax if it's an asp.net app) you configure the container and initialize the IoC (Inversion of Control):

static void Main(string[] args)
{
    var container = new WindsorContainer(new XmlInterpreter("castle.xml"));
    IoC.Initialize(container);
}

To resolve an instance you simply use the IoC:

var service = IoC.Resolve<ICustomerService();


Small remark on Dala's answer. I guess the public T Resolve<T>() method should also be static?

0

精彩评论

暂无评论...
验证码 换一张
取 消