【发布时间】:2020-03-03 15:28:43
【问题描述】:
我有以下泛型(为简洁起见删除了代码,我认为问题没有必要):
// ## 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<,>));
但是,当我尝试使用 @inject IAsyncRepository<Account> accountRepository 注入我的 razor 页面时,我收到一条错误消息:
System.ArgumentException:实现类型“AsyncRepository`1[Account]”无法转换为服务类型“IAsyncRepository`1[Account]”
但是,如果我将最终的 AsyncRepository 类的声明更改如下,那么它可以工作:
public class AsyncRepository<TEntity> : IAsyncRepository<TEntity>
where TEntity : Entity
不幸的是,我现在有代码重复,因为我需要重新实现接口。
有没有办法解决这个问题?
【问题讨论】:
-
可行吗:
services.AddScoped(typeof(IAsyncRepository<Account>), typeof(AsyncRepository<Account>));? -
@aguafrommars 不,这也行不通。如果我添加您建议的行,应用程序会在
Main函数期间崩溃,并出现与上述相同的错误。 -
和:
public class AsyncRepository<TEntity> : AsyncRepository<string, TEntity>, IAsyncRepository<TEntity> where TEntity : Entity { ... }? -
@aguafrommars 啊哈,确实有效!!
标签: c# asp.net-core generics dependency-injection blazor