我正在开发一个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 个类型 参数
我尝试过的相同代码,但使用非通用接口并且工作正常。
如何修复错误? 稍微解释一下可能非常有用。谢谢。
您有两个选项,第一个是注册特定的过滤器类型
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
}
}