使用依赖注入时如何将通用接口解析为通用实现?

时间:2018-11-01 12:17:41

标签: c# asp.net-core dependency-injection

我创建了一个我想在服务中使用的通用存储库。

public abstract class AbstractBaseRepository<TEntity, TEntityKey>
        : IBaseRepository<TEntity, TEntityKey>
        where TEntity : class, IBaseEntity<TEntityKey>, new() { /* some code */ }

和界面:

public interface IBaseRepository<TEntity, TEntityKey> { /* some code */ }

在我的服务中,我像这样注入存储库:

public class TenantsService : AbstractBaseService<TenantEntity, int>
{
    public TenantsService(IBaseRepository<TenantEntity, int> tenantsRepository)
        : base(tenantsRepository) { }
}

在启动时,在 ConfigureServices 方法上,我有:

services.AddScoped(typeof(IBaseRepository<,>), typeof(AbstractBaseRepository<,>));  

我根据以下两个答案添加了此启动代码:

https://stackoverflow.com/a/33567396

https://stackoverflow.com/a/43094684

运行应用程序时,出现以下错误:

  

无法实例化实现类型   'Playground.Repositories.Base.AbstractBaseRepository`2 [TEntity,TEntityKey]'   服务类型   'Playground.Repositories.Base.IBaseRepository`2 [TEntity,TEntityKey]'

1 个答案:

答案 0 :(得分:1)

尝试一下:

services.AddScoped(typeof(IBaseRepository<TenantEntity, int>), typeof(TenantsService));

正如柯克·拉金(Kirk Larkin)在评论中提到的那样,您是在告诉它为abstract实例化一个services.AddScoped(typeof(IBaseRepository<,>), typeof(AbstractBaseRepository<,>));类,这是无法完成的。

相关问题