首页 > 解决方案 > 将 DbContext 注入到动态注入的服务中,WepApi .netcore3.1 应用程序

问题描述

我正在向 webApi .netCore3.1 应用程序动态注入服务。
注入在“DynamicLoaderServiceImpl”服务中。使用反射从目录中的 .dll 文件加载的服务。
按照 .net api 文档中的建议注入的 DbContext。
获取 System.AggregateExcpetion。静态服务注入也不例外。
将 DBContext 作为所有服务注入。借助标记接口的作用域生命周期,然后在注入的服务构造函数中初始化,也可以正常工作。
我想我在依赖注入流程或实体框架流程中遗漏了一些东西。我无法弄清楚问题所在。

public class Startup
{
   ...
  public void ConfigureServices(IServiceCollection services)
  {   
      services.AddDbContext<RegisterUserContext>(options =>
          options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

      services.AddSingleton<IConfiguration>(provider => Configuration);
      services.AddSingleton(MappingConfig.RegisterMaps().CreateMapper());

      //dynamic services injection
      new DynamicLoaderServiceImpl().LoadServices(services, "Services");

      //static services injection
      //services.AddScoped(typeof(IDalRegisterUserService),
      //     typeof(DalEFRegisterUserServiceImpl));

      services.AddControllers();
  }
}
public void LoadServices(IServiceCollection services, string path)
{
    ...
    var loaderAttribute = type.GetCustomAttribute<LoaderAttribute>();
    if (loaderAttribute != null)
    {
         switch (loaderAttribute.Policy)
         {
             case Policy.Transient:
                services.AddTransient(loaderAttribute.InterfaceType, 
                         loaderAttribute.ImplementationType);
             break;
             case Policy.Scoped:
                services.AddScoped(loaderAttribute.InterfaceType, 
                         loaderAttribute.ImplementationType);
             break;
             case Policy.Singelton:
                services.AddSingleton(loaderAttribute.InterfaceType, 
                         loaderAttribute.ImplementationType);
             break;
         }
    }
}
public enum Policy
{
    Transient,
    Scoped,
    Singelton
}

public class LoaderAttribute : Attribute
{
    public Type InterfaceType { get; private set; }
    public Type ImplementationType { get; private set; }
    public Policy Policy { get; set; }

    public LoaderAttribute(Type interfaceType, Type implementationType, Policy policy)
    {
        InterfaceType = interfaceType;
        ImplementationType = implementationType;
        Policy = policy;
    }
}
public interface IDalRegisterUserService
{
    Task<ServiceResponse<RegisterUserResDTO>> RegisterUser(RegisterUserReqDTO user);
}
[LoaderAttribute(typeof(IDalRegisterUserService), typeof(DalEFRegisterUserServiceImpl), 
        Policy.Scoped)]
public class DalEFRegisterUserServiceImpl : IDalRegisterUserService
{
    private readonly RegisterUserContext _DbContext;
      
    public DalEFRegisterUserServiceImpl(RegisterUserContext dbContext)
    {
         _DbContext = dbContext;
    }
}
System.AggregateException
  HResult=0x80131500
  Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: IMS_DAL_RegisterUser.IDalRegisterUserService Lifetime: Scoped ImplementationType: IMS_Dal_EF_RegisterUserService.DalEFRegisterUserServiceImpl': Unable to resolve service for type 'IMS_Dal_EF_RegisterUserService.RegisterUserContext' while attempting to activate 'IMS_Dal_EF_RegisterUserService.DalEFRegisterUserServiceImpl'.)
  Source=Microsoft.Extensions.DependencyInjection
  StackTrace:
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, IServiceProviderEngine engine, 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 IMS_Services_RegisterUser.Program.Main(String[] args) in E:\Projects\IMS.EF.NET3.1\IMS.EF.NET3.1\IMS_Services_RegisterUser\Program.cs:line 16

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor 'ServiceType: IMS_DAL_RegisterUser.IDalRegisterUserService Lifetime: Scoped ImplementationType: IMS_Dal_EF_RegisterUserService.DalEFRegisterUserServiceImpl': Unable to resolve service for type 'IMS_Dal_EF_RegisterUserService.RegisterUserContext' while attempting to activate 'IMS_Dal_EF_RegisterUserService.DalEFRegisterUserServiceImpl'.

Inner Exception 2:
InvalidOperationException: Unable to resolve service for type 'IMS_Dal_EF_RegisterUserService.RegisterUserContext' while attempting to activate 'IMS_Dal_EF_RegisterUserService.DalEFRegisterUserServiceImpl'.

标签: entity-framework.net-coredependency-injectionmicroservicesdynamic-loading

解决方案


推荐阅读