Castle Windsor - 注册组件

时间:2014-03-27 03:14:22

标签: castle-windsor windsor-3.0

我创建了一个通用的静态类,用于在解决方案范围内注册组件。

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
            );
    }

但是,我无法编译它。有什么想法吗?

类型'I'必须是引用类型才能在泛型类型或方法'Castle.MicroKernel.Registration.Component.For()'

中将其用作参数'TService'

2 个答案:

答案 0 :(得分:1)

如警告所示,I需要是引用类型,因此需要通用约束来约束它

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

您可能还想查看使用IWindsorInstaller类型向容器注册组件,然后使用安装程序向容器注册组件

例如

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>());
    }
}

然后在实例化容器时

var container = new WindsorContainer();

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

答案 1 :(得分:0)

如果要解析已注册的类型,则应使用IWindsorContainer的相同实例。

如果您使用IWindsorContainer的另一个实例,则无法解决类型。