Castle Windsor - Resolving a generic implementation to a base type
I'm trying to use Windsor as a factory to provide specification implementations based on subtypes of XAbstractBase
(an abstract message base class in my case).
I have code like the following:
public abstract class XAbstractBase { }
public class YImplementation : XAbstractBase { }
public class ZImplementation : XAbstractBase { }
public interface ISpecification<T> where T : XAbstractBase
{
bool PredicateLogic();
}
public class DefaultSpecificationImplementation : ISpecification<XAbstractBase>
{
public bool PredicateLogic() { return true; }
}
public class SpecificSpecificationImplementation : ISpecification<YImplementation>
{
public bool Predi开发者_如何学JAVAcateLogic() { /*do real work*/ }
}
My component registration code looks like this:
container.Register(
AllTypes.FromAssembly(Assembly.GetExecutingAssembly())
.BasedOn(typeof(ISpecification<>))
.WithService.FirstInterface()
)
This works fine when I try to resolve ISpecification<YImplementation>
; it correctly resolves SpecificSpecificationImplementation
.
However, when I try to resolve ISpecification<ZImplementation>
Windsor throws an exception:
"No component for supporting the service ISpecification'1[ZImplementation, AssemblyInfo...] was found"
Does Windsor support resolving generic implementations down to base classes if no more specific implementation is registered?
See this post.
Update
Ok, I see now what you're doing wrong. You have no service for ISpecification<ZImplementation>
, hence it's not surprising that Windsor can't resolve it.
It's not a Windsor issue at all.
You can register it as an open generic to provide a fallback, e.g.
public class DefaultSpecificationImplementation<T> : ISpecification<T>
where T : XAbstractBase
{
public bool PredicateLogic() { return true; }
}
as
Component.For(typeof(ISpecification<>))
.ImplementedBy(DefaultSpecificationImplementation<>)
Then when Windsor can't find a specific implementation, it will use the generic one
精彩评论