【问题标题】:Dependency Injection for Generic Repository通用存储库的依赖注入
【发布时间】:2018-05-02 17:49:19
【问题描述】:

用 3 个参数注册 Generic 类的方法是什么

public interface ITest<T,V,VE>
{

}

public class TestRespository<T,V,VE>:ITest<T,V,VE>
{

}

我是这样注册的

services.AddScoped(typeof(ITest<,,>), typeof(ITest<,,>));

但无法进入构造函数以及

service.GetService(typeof(ITest<TestClass, vTestClass, VETestClass>)) as ITest<TestClass, vTestClass, VETestClass>;

【问题讨论】:

    标签: c# asp.net-mvc asp.net-core unity-container


    【解决方案1】:
    services.AddScoped(typeof(ITest<,,>), typeof(ITest<,,>));
    

    你需要implementation 和interface 而不是interface 两次。您将interface 注册为interface,所以它不能是instantiated。

    services.AddScoped(typeof(ITest<,,>), typeof(TestRepository<,,>));
    

    应该做的伎俩。

    【讨论】:

      【解决方案2】:

      问题在于调用AddScoped() 方法。您应该在第二个参数中传递实现类型,而不是接口本身的类型:

      services.AddScoped(typeof(ITest<,,>), typeof(TestRespository<,,>));
      

      【讨论】:

      • 感谢您的回答。我已经更改了您所说的内容,但它不起作用。它以 Null 的形式出现
      • 奇怪,对我来说很好用。您能否用您的代码的确切副本更新您的问题?小事很重要,现在还不清楚问题出在哪里。
      猜你喜欢
      • 2017-06-12
      • 2021-01-02
      • 2010-11-27
      • 2022-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      相关资源
      最近更新 更多