.NET DI注册开放泛型报错求助(从Autofac迁移)
从Autofac迁移至.NET DI时开放泛型注册异常问题
项目处于早期阶段,正在从Autofac迁移到.NET DI,注册开放泛型时遇到异常。
注册代码如下:
services.AddScoped(typeof(IDeviceRepository<>), typeof(DeviceRepository<>));
调用ServiceProvider = ServiceCollection.BuildServiceProvider();时抛出以下异常:
System.ArgumentException: Cannot instantiate implementation type 'Core.Repositories.DeviceRepository`1[T]' for service type 'Core.Repositories.Interfaces.IRepository`1[T]'. at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.Populate() at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory..ctor(ICollection`1 descriptors) at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options) at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options) at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services) at Avalonia.GUI.App.OnFrameworkInitializationCompleted() in C:\Users\jjjjjjjjjjjjjj\Programming\Avalonia.GUI\App.axaml.cs:line 30 at Avalonia.Controls.AppBuilderBase`1.Setup() in /_/src/Avalonia.Controls/AppBuilderBase.cs:line 312 at Avalonia.Controls.AppBuilderBase`1.SetupWithLifetime(IApplicationLifetime lifetime) in /_/src/Avalonia.Controls/AppBuilderBase.cs:line 179 at Avalonia.ClassicDesktopStyleApplicationLifetimeExtensions.StartWithClassicDesktopLifetime[T](T builder, String[] args, ShutdownMode shutdownMode) in /_/src/Avalonia.Controls/ApplicationLifetimes/ClassicDesktopStyleApplicationLifetime.cs:line 208 at Avalonia.GUI.Program.Main(String[] args) in C:\Users\jjjjjjjjjj\Programming\Avalonia.GUI\Program.cs:line 12
疑惑点:报错中涉及的IRepository是IDeviceRepository的基接口,相关类型定义如下:
实现类定义:
public class DeviceRepository<T> : RepositoryBase<T>, IDeviceRepository<T> where T : class, IDevice
接口定义:
public interface IDeviceRepository<T> : IRepository<T> where T : class, IDevice
其中RepositoryBase是抽象类,已实现IRepository接口。
此外,还通过以下代码按命名约定自动注册类型:
var typesWithInterface = Assembly.Load(Assembly.GetExecutingAssembly().GetName().Name!) .GetTypes() .Where(t => GetMatchingInterface(t) is not null);
尝试跳过抽象类但未解决问题。
编辑1:已定位到问题出在上述自动注册代码,后续调用GetInterfaces()时获取到了基接口。现在报错仍存在,但服务类型变为IDeviceRepository。
编辑2:Stack Overflow上关于注册部分封闭泛型的旧答案是否依然有效?
内容的提问来源于stack exchange,提问作者Erythana
相关产品推荐
相关产品推荐

