首页 > 解决方案 > 使用依赖注入时如何将通用接口解析为通用实现?

问题描述

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

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.IBaseRepository`2[TEntity,TEntityKey]”实例化实现类型“Playground.Repositories.Base.AbstractBaseRepository`2[TEntity,TEntityKey]”

标签: c#asp.net-coredependency-injection

解决方案


试试这个:

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

正如 Kirk Larkin 在评论中提到的,你告诉它实例化一个它不能做的abstract类。services.AddScoped(typeof(IBaseRepository<,>), typeof(AbstractBaseRepository<,>));


推荐阅读