在Unity依赖注入中注入IEnumerable通用接口c#
问题描述:
我正在使用Web API 2应用程序并使用Unity依赖注入。在Unity依赖注入中注入IEnumerable通用接口c#
我有多种类型的过滤器:名称,品牌,类型...
我想创建一个名为接口:IFilterService并迫使所有其他类来实现它,然后我调用该接口的IEnumerable和注入正确的类型。
界面:
public interface IFilterService<T>
{
bool CanHandle(FilterType type);
Task<ServiceResult<T>> FilterAsync(T entity);
}
和类是这样的:
public class NameService : IFilterService<Name>
{
public bool CanHandle(FacetType type)
{
return type == FacetType.Name;
}
public async Task<ServiceResult<Name>> FilterAsync(Name entity)
{
// Code
}
}
控制器是这样的:
public class FilterController
{
private readonly IEnumerable<IFilterService> filters;
public MediaController(IEnumerable<IFilterService> filters)
{
this.filters = filters;
}
public async Task<HttpResponseMessage> FilterAsync(FilterType type, Name entity)
{
foreach(var filter in this.filters.Where(x => x.CanHandle(type)))
{
filter.FilterAsync(entity);
}
....
}
}
一切正常:唯一的问题是在Unity依赖注入中注册接口和类。
container.RegisterType<IEnumerable<IFilterService>, IFilterService[] >(
new ContainerControlledLifetimeManager());
container.RegisterType<IFilterService, NameService>("Name Service",
new ContainerControlledLifetimeManager());
我收到此错误:
Error CS0305 Using the generic type 'IFilterService' requires 1 type arguments
相同的代码我已经试过了,但与非通用接口和正常工作。
如何解决错误?一些解释可能会非常有用。谢谢。
答
你有两个选择,第一是注册特定的过滤器类型
container.RegisterType<IEnumerable<IFilterService<Name>>, IFilterService<Name>[] >(
new ContainerControlledLifetimeManager());
container.RegisterType<IFilterService<Name>, NameService>("Name Service",
new ContainerControlledLifetimeManager());
一样使用
public class FilterController
{
private readonly IEnumerable<IFilterService<Name>> filters;
public MediaController(IEnumerable<IFilterService<Name>> filters)
{
this.filters = filters;
}
public async Task<HttpResponseMessage> FilterAsync(FilterType type, Name entity)
{
foreach(var filter in this.filters.Where(x => x.CanHandle(type)))
{
filter.FilterAsync(entity);
}
....
}
}
第二个选项是让你的接口不通用的,但你保持功能通用
public interface IFilterService
{
bool CanHandle(FilterType type);
Task<ServiceResult<T>> FilterAsync<T>(T entity);
}
public class NameService : IFilterService
{
public bool CanHandle(FacetType type)
{
return type == FacetType.Name;
}
public Task<ServiceResult<T>> FilterAsync<T>(T entity)
{
if(!entity is Name)
throw new NotSupportedException("The parameter 'entity' is not assignable to the type 'Name'");
return FilterAsyncInternal((Name)entity);
}
private async Task<ServiceResult<Name>> FilterAsyncInternal(Name entity)
{
//code
}
}
第二个解决方案中的返回值是什么? –
'Task>'从您的示例控制器返回,'Task >'中的'T'将是'实体'类型。 –
我更新了第二个示例,使其更清楚地将它分解为两个函数来返回。 –