我正在开发一个 Web API 2 应用程序并使用 Unity 依赖注入。
我有多种类型的过滤器:名称、品牌、类型...
我想创建一个名为: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());
我收到此错误:
错误 CS0305 使用泛型类型“IFilterService”需要 1 个类型参数
我尝试过的相同代码但具有非通用接口并且工作正常。
如何修复错误?一点解释可能会非常有用。谢谢你。