首页 > 解决方案 > 通用接口、实现和依赖注入 - 实现类型不能转换为服务类型

问题描述

我有以下泛型(为简洁起见删除了代码,我认为这个问题没有必要):

// ## 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

不幸的是,我现在有代码重复,因为我需要重新实现接口。

有没有办法解决?

标签: c#asp.net-coregenericsdependency-injectionblazor

解决方案


您的存储库必须实现IAsyncRepository<TEntity>:更新您的AsyncRepository<TEntity>声明:

public class AsyncRepository<TEntity> : AsyncRepository<string, TEntity>,
IAsyncRepository<TEntity>
where TEntity : Entity { ... }

推荐阅读