C# 在使用依赖项注入时,如何将泛型接口解析为泛型实现?
我已经创建了一个要在服务中使用的通用存储库C# 在使用依赖项注入时,如何将泛型接口解析为泛型实现?,c#,asp.net-core,dependency-injection,C#,Asp.net Core,Dependency Injection,我已经创建了一个要在服务中使用的通用存储库 public abstract class AbstractBaseRepository<TEntity, TEntityKey> : IBaseRepository<TEntity, TEntityKey> where TEntity : class, IBaseEntity<TEntityKey>, new() { /* some code */ } 公共抽象类AbstractB
public abstract class AbstractBaseRepository<TEntity, TEntityKey>
: IBaseRepository<TEntity, TEntityKey>
where TEntity : class, IBaseEntity<TEntityKey>, new() { /* some code */ }
公共抽象类AbstractBaseRepository
:IBaseRepository
其中tenty:class,IBaseEntity,new(){/*一些代码*/}
以及界面:
public interface IBaseRepository<TEntity, TEntityKey> { /* some code */ }
public interface IBaseRepository{/*some code*/}
在我的服务中,我按如下方式注入存储库:
public class TenantsService : AbstractBaseService<TenantEntity, int>
{
public TenantsService(IBaseRepository<TenantEntity, int> tenantsRepository)
: base(tenantsRepository) { }
}
公共类租户服务:AbstractBaseService
{
公共租户服务(IBaseRepository租户存储库)
:base(租户存储库){}
}
在启动时,在ConfigureServices方法上,我有:
services.AddScoped(typeof(IBaseRepository<,>), typeof(AbstractBaseRepository<,>));
services.addScope(typeof(IBaseRepository)、typeof(AbstractBaseRepository));
我根据以下两个答案添加了此启动代码:
当我运行应用程序时,出现以下错误:
无法实例化实现类型
'游乐场.Repositories.Base.AbstractBaseRepository'2[tenty,TEntityKey]'
对于服务类型
'游乐场.仓库.基地.IBaseRepository'2[TEntity,TEntityKey]'
试试这个:
services.AddScoped(typeof(IBaseRepository<TenantEntity, int>), typeof(TenantsService));
services.addScope(typeof(IBaseRepository)、typeof(TenantsService));
正如Kirk Larkin在评论中提到的,您告诉它为
服务实例化一个抽象类代码>它不能做。你试过在startup.cs中用AddSingleton代替addScope吗?你要求DI容器实例化一个抽象的类,这个类不能实例化。这很有意义。难道没有办法指定我们希望接口解析为任何扩展给定类的类吗?在本例中,任何扩展AbstractBaseRepository的类?有关此类额外功能,请参阅文档中的。另一个选项是使用类似的东西。您需要的是是否有一个程序集扫描功能,允许您自动注册通用抽象的所有非通用实现。答案是:不,这种功能不存在的开箱即用。我同意@KirkLarkin的观点,Scrutor在ASP.NET内核的内置容器上添加了这个缺失的功能。