[英]Generic Interface, Implementation and Dependency Injection - Implementation Type Can't Be Converted To Service Type
I have the following generics (code removed for brevity, I don't think its necessary for the question):我有以下泛型(为简洁起见,删除了代码,我认为这个问题没有必要):
// ## 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 { ... }
I then dependency-inject the AsyncRepositories
as follows:然后我依赖注入AsyncRepositories
如下:
services.AddScoped(typeof(IAsyncRepository<>), typeof(AsyncRepository<>));
services.AddScoped(typeof(IAsyncRepository<,>), typeof(AsyncRepository<,>));
However, when I attempt to inject into my razor
page using @inject IAsyncRepository<Account> accountRepository
, I get an error saying:但是,当我尝试使用@inject IAsyncRepository<Account> accountRepository
注入我的razor
页面时,我收到一条错误消息:
System.ArgumentException: Implementation type 'AsyncRepository`1[Account]' can't be converted to service type 'IAsyncRepository`1[Account]' System.ArgumentException:无法将实现类型“AsyncRepository`1[Account]”转换为服务类型“IAsyncRepository`1[Account]”
But, if I change the declaration of the final AsyncRepository
class as follows then it works:但是,如果我按如下方式更改最终AsyncRepository
类的声明,则它可以工作:
public class AsyncRepository<TEntity> : IAsyncRepository<TEntity>
where TEntity : Entity
Unfortunately I now have code duplication as I need to re-implement the interface.不幸的是,我现在有代码重复,因为我需要重新实现接口。
Is there any way around this?有没有办法解决?
Your repository must implement IAsyncRepository<TEntity>
: update your AsyncRepository<TEntity>
declaration with :您的存储库必须实现IAsyncRepository<TEntity>
:使用以下内容更新您的AsyncRepository<TEntity>
声明:
public class AsyncRepository<TEntity> : AsyncRepository<string, TEntity>,
IAsyncRepository<TEntity>
where TEntity : Entity { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.