【问题标题】:How to injection a generic interface with .NET Core如何使用 .NET Core 注入通用接口
【发布时间】:2021-05-28 03:33:43
【问题描述】:

我有下一个错误:

System.ArgumentException: '无法实例化实现类型

要注入的接口:

public interface iContext<T> { }

这个界面怎么用?

public class UsersRepository : iUsersRepository
{
    readonly iContext<UserEntities> db;
    public UsersRepository(iContext<UserEntities> db)
    {
        this.db = db;
    }
}

如何在启动时添加:

//services.AddScoped(typeof(iContext<>), typeof(UserEntities));
services.AddScoped(typeof(iContext<>));
//services.AddTransient<iContext<UserEntities>>();
//services.AddSingleton<iContext<UserEntities>, UserEntities>();

已编辑:

System.ArgumentException: Cannot instantiate implementation type 'Infrastructure._01_DataAccess.iContext`1[T]' for service type 'Infrastructure._01_DataAccess.iContext`1[T]'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.Populate()
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory..ctor(IEnumerable`1 descriptors)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine..ctor(IEnumerable`1 serviceDescriptors, IServiceProviderEngineCallback callback)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CompiledServiceProviderEngine..ctor(IEnumerable`1 serviceDescriptors, IServiceProviderEngineCallback callback)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
   at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at WebApi.Program.Main(String[] args) in C:\Users\Daviel.SPAIN-HOLIDAY\Source\Repos\dhmaker-user\WebApi\Program.cs:line 16

【问题讨论】:

  • 很难重现问题,因为您没有提供完整的异常消息,没有添加完整的堆栈跟踪,也没有显示UserEntities 实现。请提供minimal, reproducible example。
  • @Steven 我编辑时出错
  • 作为建议,接口的命名约定,“i”需要大写。 “iUsersRepository”变成“IUsersRepository”。

标签: .net-core dependency-injection interface


【解决方案1】:

你需要注册一个实现iContext&lt;T&gt;的具体类,像这样:

services.AddScoped(typeof(iContext&lt;&gt;), typeof(Context&lt;&gt;));

其中Context&lt;T&gt; 是实现iContext&lt;T&gt; 的类。

【讨论】:

  • 嗨。我试试这个,但我收到同样的错误
  • 你能解决UserEntities 和IContext&lt;T&gt; impelementation 的任何/所有其他依赖项吗?
猜你喜欢
  • 1970-01-01
  • 2020-09-04
  • 1970-01-01
  • 2019-07-22
  • 1970-01-01
  • 1970-01-01
  • 2020-08-22
  • 2015-04-26
  • 1970-01-01
相关资源
最近更新 更多