在温莎城堡注册通用抽象类 [英] Registering a generic abstract class in Castle Windsor

查看:82
本文介绍了在温莎城堡注册通用抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照约定注册类型,在此示例中,我简化了案例:

I am trying to register a type by convention, I've simplified my case in this example:

public abstract class BaseEntity{}

public class EntityA : BaseEntity{}

public class EntityB : BaseEntity{}

public abstract class BaseClass
{
    //...
}

public abstract class GenericBaseClass<T> : BaseClass where T : BaseEntity
{
    //..
}

public class ConcreteA : GenericBaseClass<EntityA>
{
    //...
}

public class ConcreteB : GenericBaseClass<EntityB>
{
    //...
}

我正在尝试寻找注册GenericBaseClass以便在请求GenericBaseClass<EntityA>时返回ConcreteA的方法.尝试解决此问题时,出现异常,例如:

I'm trying to find the way to register GenericBaseClass to return ConcreteA when requesting for GenericBaseClass<EntityA>. When trying to resolve this, I get an exception saying something like:

尝试获取类型的实例时发生激活错误 GenericBaseClass`1,键"

Activation error occured while trying to get instance of type GenericBaseClass`1, key ""

如果将GenericBaseClass<T>的定义从抽象类更改为接口,则此注册代码有效:

If I change the definition of GenericBaseClass<T> from an abstract class to an interface, this registration code works:

container.Register(AllTypes.FromAssemblyContaining<BaseClass>()
         .BasedOn(typeof(GenericBaseClass<>))
         .WithService.FirstInterface());

但是,我需要使用抽象类,因为我需要在其中编写代码. 我可以手动注册每个ConcreteX类,但这不会很有帮助.

However, I need to use an abstract class because I need to write code inside of it. I can register manually every ConcreteX class, but it wouldn't be very helpful.

我已经尝试过了:

container.Register(AllTypes.FromAssemblyContaining<BaseClass>()
         .BasedOn(typeof(GenericBaseClass<>))
         .WithService.Base());

调试,我可以看到类型没有添加到容器中.

Debugging, I can see the type is not added to the container.

我正在使用温莎城堡2.6.

I am using Castle Windsor 2.6.

谢谢.

推荐答案

这有效:

container.Register(AllTypes.FromAssemblyContaining<ConcreteA>()
                    .BasedOn(typeof (GenericBaseClass<>))
                    .WithService.Base());

如果您看到没有添加到容器中的类型,请确保您正在扫描正确的程序集(其中包含实现类型,而不是服务类型).

If you see types not being added to the container make sure you're scanning the right assembly (the one which contains implementation types, not the service types).

这篇关于在温莎城堡注册通用抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆