问题
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>
{
//...
}
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:
Activation error occured while trying to get instance of type GenericBaseClass`1, key ""
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());
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.
I've tried with this:
container.Register(AllTypes.FromAssemblyContaining<BaseClass>()
.BasedOn(typeof(GenericBaseClass<>))
.WithService.Base());
Debugging, I can see the type is not added to the container.
I am using Castle Windsor 2.6.
Thanks.
回答1:
This works:
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).
来源:https://stackoverflow.com/questions/7901937/registering-a-generic-abstract-class-in-castle-windsor