Register all classes from base on up in Castle Windsor using Fluent interface

天涯浪子 提交于 2019-12-06 08:44:18
codekaizen

We had a simliar problem to this, but only needed to register the first base which was abstract. I solved it using WithServiceSelect but wrapped it up into an extension method to be used so:

AllTypes.FromAssembly(assembly)
        .BasedOn<Search.Search>()
        .WithServiceLastAbstractBase(),

The definition of the extension method is:

public static BasedOnDescriptor WithServiceLastAbstractBase(this BasedOnDescriptor basedOn)
{
    return basedOn.WithServiceSelect(selectLastAbstractBase);
}

private static IEnumerable<Type> selectLastAbstractBase(Type type, Type[] basetypes)
{
    var baseType = type;

    do
    {
        baseType = baseType.BaseType;
    } while (baseType != null && !baseType.IsAbstract);

    if (baseType == null)
    {
        throw new ArgumentException("There are no abstract base types for: " + type);
    }

    return new [] { baseType };
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!