1

我正在开发一个 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 个类型参数

我尝试过的相同代码但具有非通用接口并且工作正常。

如何修复错误?一点解释可能会非常有用。谢谢你。

4

1 回答 1

2

你有两个选择,第一个是注册特定的过滤器类型

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
    }
}
于 2017-07-14T19:00:47.720 回答