Autofac 通用接口不可分配给服务

mis*_*130 1 c# dependency-injection inversion-of-control autofac

我在一个应用程序中有 20 个这样的注册:

builder.RegisterType(typeof(FilterParser<>)).As(typeof(IFilterParser<>)).InstancePerDependency();
Run Code Online (Sandbox Code Playgroud)

当我尝试构建容器时,出现如下错误:

类型“My.Namespace.FilterParser`1[TEntity]”不可分配给服务“My.Namespace.IFilterParser`1”。

请注意,区别在于[TEntity]接口中的实现和缺少。

我的服务确实实现了接口:

public class FilterParser<TEntity> : IFilterParser<TEntity> where TEntity : new () 

public interface IFilterParser<TEntity> where TEntity : new () 
Run Code Online (Sandbox Code Playgroud)

我还使用 .net core 实现了这个注册,它工作得很好,但在 Autofac 中它只是拒绝工作。

我什至尝试过AsImplementedInterfaces,但得到了同样的错误

builder.RegisterType(typeof(FilterParser<>)).AsImplementedInterfaces()
                        .InstancePerDependency();
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 5

使用RegisterGeneric()构建器方法:

builder.RegisterGeneric(typeof(FilterParser<>))
    .As(typeof(IFilterParser<>))
    .InstancePerDependency();
Run Code Online (Sandbox Code Playgroud)

当从容器中请求匹配的服务类型时,Autofac 会将其映射到实现类型的等效封闭版本

参考注册概念:开放通用组件