在 Castle Windsor 中注册通用接口的多个实现
Register multiple implementations of generic interface in Castle Windsor
我想为我的服务注册一个实现
IQueryService<TEntity, TPrimaryKey>
.
所以我的代码看起来像这样:
IocManager.IocContainer.Register(Component.For(typeof(IQueryService<,>))
.ImplementedBy(typeof(QueryService<,,,>);
我想为以 string
作为主键的实体创建一个类似的实现,我们称之为 QueryServiceString
。有没有办法把它写下来,这样 Castle Windsor 会自动选择它应该注入的class?
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);
}));
我想为我的服务注册一个实现
IQueryService<TEntity, TPrimaryKey>
.
所以我的代码看起来像这样:
IocManager.IocContainer.Register(Component.For(typeof(IQueryService<,>))
.ImplementedBy(typeof(QueryService<,,,>);
我想为以 string
作为主键的实体创建一个类似的实现,我们称之为 QueryServiceString
。有没有办法把它写下来,这样 Castle Windsor 会自动选择它应该注入的class?
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);
}));