我想为我的服务注册一个实现CCD_ 1。
所以我有这样的代码:
IocManager.IocContainer.Register(Component.For(typeof(IQueryService<,>))
.ImplementedBy(typeof(QueryService<,,,>);
我想为以string
为主键的实体创建一个类似的实现,我们称之为QueryServiceString
。有没有办法把它写下来,让温莎城堡自动选择应该注入哪个类?
IocManager.IocContainer.Register(Component.For(typeof(IQueryService<,STRING?>))
.ImplementedBy(typeof(QueryServiceString<,,>)
部分打开的泛型类型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);
}));