c# - 使用依赖注入时如何将通用接口解析为通用实现?
问题描述
我创建了一个我想在服务中使用的通用存储库。
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]”
解决方案
试试这个:
services.AddScoped(typeof(IBaseRepository<TenantEntity, int>), typeof(TenantsService));
正如 Kirk Larkin 在评论中提到的,你告诉它实例化一个它不能做的abstract
类。services.AddScoped(typeof(IBaseRepository<,>), typeof(AbstractBaseRepository<,>));
推荐阅读
- c# - ViewBag 不刷新
- c - C问题:程序自行终止
- javascript - 我需要从函数外部访问 JSON 数据
- javascript - 带有参数的 vue-router 无法在 netlify 上运行部署
- html - 如何包含带有 html5 视频标签的 .ass 字幕文件
- jupyter-notebook - 无法在浏览器中启动 Jupyter 实验室或 Jupyter 笔记本
- apache-spark - Livy REST Spark java.io.FileNotFoundException:
- scroll - 在 Flutter 中为对角滚动的背景图案设置动画
- typescript - ParentType 不可分配给类型 T(扩展 ParentType)
- sql - 找到和室友一样的薪水