IoC and DI with Castle.Windsor

Castle.Windsor is the most complete and diffused IoC Container for .Net (is more powerful than Ninject).

To configure the IoC Container we have to specify the mapping between each interface and its concrete class. This can be done within a class which implements the IWindsorInstaller interface:

class CastleInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Component.For<IDependency1>().ImplementedBy<Dependency1>());
        container.Register(Component.For<IDependency2>().ImplementedBy<Dependency2>());
        container.Register(Component.For<IDependency3>().ImplementedBy<Dependency3>());
        container.Register(Component.For<IDependency4>().Instance(new Dependency()
        {
            Property1 = "Value1",
            Property2 = "Value2",
            Property3 = "Value3",
        }));
    }
}

After the configuration has been defined we can create the container and use it to resolve our instances. Castle will automatically resolve each dependency with the configured object:

static void Main(string[] args)
{
    //Creates Castle Container
    WindsorContainer container = new WindsorContainer();
    container.Install(new CastleInstaller());
 
    //Resolves MarshallFeed Service
    IMarshallFeedService service = container.Resolve<IMarshallFeedService>();
 
    ...
 
    //Releases MarshallFeed Service
    container.Release(service);
}

Automatically installing all the installer within an assembly

Instead of providing a specific instance of the installer to the container.Install() method (as in the example above) we can tell Castle to find all the installers within the assembly and to install them:

container.Install(FromAssembly.This());
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s