c# - 通用接口、实现和依赖注入 - 实现类型不能转换为服务类型
问题描述
我有以下泛型(为简洁起见删除了代码,我认为这个问题没有必要):
// ## Entity interface
public interface IEntity<TPrimaryKey>
{
TPrimaryKey Id { get; set; }
}
// ## Entity implementations
public class Entity<TPrimaryKey> : IEntity<TPrimaryKey> { ... }
public class Entity : Entity<string> { ... }
// ## Repo interfaces
public interface IAsyncRepository<TPrimaryKey, TEntity>
where TEntity : Entity<TPrimaryKey> { ... }
public interface IAsyncRepository<TEntity> : IAsyncRepository<string, TEntity>
where TEntity : Entity<string> {...}
// ## Repo implementations
public class AsyncRepository<TPrimaryKey, TEntity>
: IAsyncRepository<TPrimaryKey, TEntity>
where TEntity : Entity<TPrimaryKey> { ... }
public class AsyncRepository<TEntity> : AsyncRepository<string, TEntity>
where TEntity : Entity { ... }
然后我依赖注入AsyncRepositories
如下:
services.AddScoped(typeof(IAsyncRepository<>), typeof(AsyncRepository<>));
services.AddScoped(typeof(IAsyncRepository<,>), typeof(AsyncRepository<,>));
但是,当我尝试使用 注入我的razor
页面时@inject IAsyncRepository<Account> accountRepository
,我收到一条错误消息:
System.ArgumentException:实现类型“AsyncRepository`1[Account]”无法转换为服务类型“IAsyncRepository`1[Account]”
AsyncRepository
但是,如果我按如下方式更改最终类的声明,则它可以工作:
public class AsyncRepository<TEntity> : IAsyncRepository<TEntity>
where TEntity : Entity
不幸的是,我现在有代码重复,因为我需要重新实现接口。
有没有办法解决?
解决方案
您的存储库必须实现IAsyncRepository<TEntity>
:更新您的AsyncRepository<TEntity>
声明:
public class AsyncRepository<TEntity> : AsyncRepository<string, TEntity>,
IAsyncRepository<TEntity>
where TEntity : Entity { ... }
推荐阅读
- java - 加装手柄 助焊剂返回型
- android - tns 医生说缺少“ANDROID_HOME”,即使它设置在 circleCi
- sql - SQL Server 中没有 Order By 子句的 SQL Select 语句的顺序
- python - 在 Heroku 上安装 ODBC 驱动程序
- c - C 程序:getenv 在 GDB/DDD 中返回 NULL
- javascript - html2canvas 无法加载图像未定义
- php - SQLSTATE [HY000]:一般错误:1364 字段“角色”没有默认值
- ios - 用于检查是否在数组中找到特定 id 的 For 循环
- jquery - FlexSlider itemWidth 未在窗口调整大小时更新
- c - 如何制作CAN协议的传输代码