在Castle Windsor中注册通用接口的多种实现

我想为我的服务注册一个实现 IQueryService<TEntity,TPrimaryKey>

所以我有如下代码:

IocManager.IocContainer.Register(Component.For(typeof(IQueryService<,>))
    .ImplementedBy(typeof(QueryService<,>);

我想为string作为主键的实体创建一个类似的实现,我们称之为QueryServiceString。有没有办法将它写下来,以便温莎城堡将自动选择应该注入的课程?

IocManager.IocContainer.Register(Component.For(typeof(IQueryService<,STRING?>))
    .ImplementedBy(typeof(QueryServiceString<,>)
songyish 回答:在Castle Windsor中注册通用接口的多种实现

部分打开的通用类型IQueryService<,STRING?>是无效的语法。

您可以注册工厂方法并根据通用参数解析类型:

IocManager.IocContainer.Register(Component.For(typeof(QueryService<,>)));
IocManager.IocContainer.Register(Component.For(typeof(QueryServiceString<>)));

IocManager.IocContainer.Register(Component.For(typeof(IQueryService<,>))
    .UsingFactoryMethod((kernel,creationContext) =>
    {
        Type type = null;

        var tEntity = creationContext.GenericArguments[0];
        var tPrimaryKey = creationContext.GenericArguments[1];
        if (tPrimaryKey == typeof(string))
        {
            type = typeof(QueryServiceString<>).MakeGenericType(tEntity);
        }
        else
        {
            type = typeof(QueryService<,>).MakeGenericType(tEntity,tPrimaryKey);
        }

        return kernel.Resolve(type);
    }));
本文链接:https://www.f2er.com/3110289.html

大家都在问