Castle Windsor - Registering components

4.5k Views Asked by At

I have created a common static class for registering components solution wide.

private static readonly IWindsorContainer Container = new WindsorContainer();

public static void Register<I, T>() where T : I
    {
        Container.Register(
            Component.For<I>().ImplementedBy<T>().LifeStyle.Transient
            );
    }

However, I am not able to compile it. Any ideas?

The type 'I' must be a reference type in order to use it as parameter 'TService' in the generic type or method 'Castle.MicroKernel.Registration.Component.For()'

2

There are 2 best solutions below

0
Russ Cam On BEST ANSWER

As the warning indicates, I needs to be a reference type so it requires a generic constraint to constrain it as such

public static void Register<I, T>() where T : I where I : class
{
    Container.Register(
        Component.For<I>().ImplementedBy<T>().LifestyleTransient());
}

You may also want to look at using IWindsorInstaller types for registering components with the container and then register components with the container using the installers

For example

public class MvcInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            // Register HttpContextBase using factory method
            Component.For<HttpContextBase>()
                     .UsingFactoryMethod(() => 
                         new HttpContextWrapper(HttpContext.Current))
                     .LifestylePerWebRequest(),
            // Convention based registration to register all controllers
            // with Windsor
            Classes.FromThisAssembly()
                   .BasedOn<IController>()
                   .If(t => t.Name.EndsWith("Controller"))
                   .Configure(c => c.LifestylePerWebRequest()),
            Component.For<IControllerFactory>()
                     .ImplementedBy<WindsorControllerFactory>());
    }
}

Then when instantiating the container

var container = new WindsorContainer();

// find all installers in the current assembly and use them to register 
// services with the container
container.Install(FromAssembly.This());
0
Ilya Palkin On

If you want to resolve registered types you should use the same instance of IWindsorContainer.

Types won't be resolved if you use another one instance of IWindsorContainer.