【发布时间】: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