【问题标题】:Generic Interface, Implementation and Dependency Injection - Implementation Type Can't Be Converted To Service Type通用接口、实现和依赖注入 - 实现类型不能转换为服务类型
【发布时间】: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&lt;Account&gt; accountRepository 注入我的 razor 页面时,我收到一条错误消息:

System.ArgumentException:实现类型“AsyncRepository`1[Account]”无法转换为服务类型“IAsyncRepository`1[Account]”

但是,如果我将最终的 AsyncRepository 类的声明更改如下,那么它可以工作:

public class AsyncRepository<TEntity> : IAsyncRepository<TEntity>
    where TEntity : Entity

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

有没有办法解决这个问题?

【问题讨论】:

  • 可行吗:services.AddScoped(typeof(IAsyncRepository&lt;Account&gt;), typeof(AsyncRepository&lt;Account&gt;)); ?
  • @aguafrommars 不,这也行不通。如果我添加您建议的行,应用程序会在 Main 函数期间崩溃,并出现与上述相同的错误。
  • 和:public class AsyncRepository&lt;TEntity&gt; : AsyncRepository&lt;string, TEntity&gt;, IAsyncRepository&lt;TEntity&gt; where TEntity : Entity { ... } ?
  • @aguafrommars 啊哈,确实有效!!

标签: c# asp.net-core generics dependency-injection blazor


【解决方案1】:

您的存储库必须实现 IAsyncRepository&lt;TEntity&gt;:更新您的 AsyncRepository&lt;TEntity&gt; 声明:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2019-10-15
    • 1970-01-01
    • 2016-11-08
    • 2015-10-18
    • 2016-05-10
    • 1970-01-01
    相关资源
    最近更新 更多