我想为我的服务注册一个实施IQueryService<TEntity, TPrimaryKey>
所以我有一个看起来像这样的代码
IocManager.IocContainer.Register(Component.For(typeof(IQueryService<,>))
.ImplementedBy(typeof(QueryService<,,,>);
而且我想为使用字符串作为主键的实体创建一个类似的实现,我们称它为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);
}));