【问题标题】:adding generic services in asp.net core DI在 asp.net core DI 中添加通用服务
【发布时间】:2017-02-22 12:13:23
【问题描述】:

在 asp.net core DI 中,具有以下内容:

public interface IRepository<T> where T:class {}
public class Repository<T> : IRepository<T> where T:class {}

我将执行以下操作来注册我的服务:

services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

但现在我的服务如下:

public interface IContextProvider<T1,T2> {}
public class ContextProviderOne<T2> : IContextProvider<ContextClass1,T2> { }
public class ContextProviderTwo<T2> : IContextProvider<ContextClass2,T2> { }

如何将我的服务添加到 DI?

【问题讨论】:

  • services.AddScoped(typeof(IRepository&lt;&gt;), typeof(IRepository&lt;&gt;)); 应该如何工作,IRepository&lt;&gt; 不能被实例化,它是一个接口,而不是一个具体的类。
  • 你的意思是说下面的注册不适用于内置容器? services.AddScoped(typeof(IContextProvider&lt;,&gt;), typeof(ContextProviderOne&lt;&gt;)); services.AddScoped(typeof(IContextProvider&lt;,&gt;), typeof(ContextProviderTwo&lt;&gt;));?
  • @Tseng:这显然是一个错字。
  • 上面写着An unhandled exception was thrown by the application. System.ArgumentException: The number of generic arguments provided doesn't equal the arity of the generic type definition. Parameter name: instantiation
  • 你找到解决这个问题的方法了吗?

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


【解决方案1】:

你试过了吗:

services.AddScoped(typeof(IContextProvider<T1>), typeof(ContextProviderOne<T1>));
services.AddScoped(typeof(IContextProvider<T2>), typeof(ContextProviderTwo<T2>));

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 2018-07-22
    • 2023-04-03
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多