问题描述
我创建了一个我想在服务中使用的通用存储库.
I have created a generic repository that I want to be used in a service.
public abstract class AbstractBaseRepository<TEntity, TEntityKey>
: IBaseRepository<TEntity, TEntityKey>
where TEntity : class, IBaseEntity<TEntityKey>, new() { /* some code */ }
和界面:
public interface IBaseRepository<TEntity, TEntityKey> { /* some code */ }
在我的服务中,我像这样注入存储库:
On my service I inject the repository like this:
public class TenantsService : AbstractBaseService<TenantEntity, int>
{
public TenantsService(IBaseRepository<TenantEntity, int> tenantsRepository)
: base(tenantsRepository) { }
}
在启动时,在 ConfigureServices 方法上,我有:
On my startup, on the ConfigureServices method, I have:
services.AddScoped(typeof(IBaseRepository<,>), typeof(AbstractBaseRepository<,>));
我根据以下两个答案添加了此启动代码:
I added this startup code based on the following two answers:
https://stackoverflow.com/a/33567396
https://stackoverflow.com/a/43094684
运行应用程序时,出现以下错误:
When I run the application I am getting the following error:
推荐答案
尝试一下:
services.AddScoped(typeof(IBaseRepository<TenantEntity, int>), typeof(TenantsService));
正如柯克·拉金(Kirk Larkin)在评论中所提到的,您是在告诉它为 services.AddScoped(typeof(IBaseRepository<,>)),typeof(AbstractBaseRepository<>));
不能做到.
As Kirk Larkin mentioned in the comments, you're telling it to instantiate an abstract
class for services.AddScoped(typeof(IBaseRepository<,>), typeof(AbstractBaseRepository<,>));
which it can't do.
这篇关于使用依赖注入时,如何将通用接口解析为通用实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!