Search code examples
c#genericscastle-windsor

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 PredicateLogic() { /*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?


Solution

  • 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.