在 Unity 依赖注入 c# 中注入通用接口的 IEnumerable

Inject an IEnumerable of generic interface in Unity Dependency Injection c#

我正在开发 Web API 2 应用程序并使用 Unity 依赖项注入。

我有多种类型的过滤器:名称、品牌、类型...

我想创建一个名为:IFilterService 的接口并强制每个其他 class 实现它,然后我调用该接口的 IEnumerable 并使用正确的类型注入它。

界面是:

public interface IFilterService<T>
{
    bool CanHandle(FilterType type);

    Task<ServiceResult<T>> FilterAsync(T entity);
}

和 class 是这样的:

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 依赖注入中注册接口和 classes。

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
    }
}