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

问题描述 投票:-1回答:1

我想为我的服务注册一个实现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<,,>)
c# generics dependency-injection castle-windsor aspnetboilerplate
1个回答
0
投票

部分打开的通用类型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);
    }));
© www.soinside.com 2019 - 2024. All rights reserved.