Currently, I'm trying to use the WindsorContainer 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.
+1
A:
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();
Dala
2009-10-15 13:52:14
innerContainer has to be of type IWindsorContainer. thanks
Femaref
2009-10-15 14:57:30
note that you should *really* try to avoid calling directly the container, otherwise you're using the container as a service locator, bad practice.
Mauricio Scheffer
2009-10-15 15:26:19
A:
Small remark on Dala's answer. I guess the public T Resolve<T>() method should also be static?
Rob van Groenewoud
2009-10-15 13:56:41
@Rob - if you have a remark about Dala's answer, you should add it in the comment section of Dala's answer ;-)
Metro Smurf
2009-10-15 14:50:49
@ Metro Smurf: I know, but my current reputation level only lets me add comments to my own answers. Once I'm upvoted some more here and there, I'd be able to use the comments as you suggest.
Rob van Groenewoud
2009-10-15 15:05:13