在 .NET Core 控制台应用程序中针对 EF Core DbContext 服务错误建立依赖注入

Established dependency injection in .NET Core Console Application for EF Core DbContext Service Error

我创建了一个 .net Core 控制台应用程序,并添加了以下依赖注入包:

Microsoft.Extensions.DependencyInjection

为了注入 EF Core DbContext 服务,下面是该项目的代码片段:

static void Main(string[] args)
        {
            // Create service collection and configure our services
            var services = ConfigureServices();

            // Generate a provider
            var serviceProvider = services.BuildServiceProvider();

            // Kick off our actual code
            serviceProvider.GetService<Startup>().Run();
        }

        public static IConfiguration LoadConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
                .AddEnvironmentVariables();

            return builder.Build();
        }


private static IServiceCollection ConfigureServices()
        {
            IServiceCollection services = new ServiceCollection();

            // Set up the objects we need to get to configuration settings
            var configuration = LoadConfiguration();


            // IMPORTANT! Register our cvonfig file, db connection string, and application entry point(startup)
            services
                .AddSingleton(configuration)
                .AddConnection(configuration)
                .AddStartup();
            
            return services;
        }

服务池CLass:

  public static class ServicesPool
    {
        public static IServiceCollection AddStartup(this IServiceCollection services)
        {
            services.AddTransient<Startup>();

            return services;
        }

        public static IServiceCollection AddConfiggguration(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddSingleton(configuration);

            return services;
        }

        public static IServiceCollection AddConnection(this IServiceCollection services, IConfiguration configuration)
        {
            var connection = configuration.GetConnectionString("DEV_CS");
            services.AddDbContext<MigrationDbContext>(options =>
            options.UseSqlServer(connection, b => b.MigrationsAssembly("migration.presentence")));

            return services;
        }

    }

从 EntityFramwork Core 实现 DbContext 的 MigrationDbContext 服务:

public class MigrationDbContext : DbContext
    {
        public MigrationDbContext(DbContextOptions dbContextOptions) : base(dbContextOptions)
        {
        }

        public DbSet<RootItemMigrationEntity> RootItems { get; set; }

    }

应用程序运行没有任何问题,但是当我尝试使用以下命令创建初始迁移时:

Add-Migration 'Initial'

出现错误并显示以下消息:

Unable to create an object of type 'MigrationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

我一直在调查这个问题,我已经尝试了多种解决方案,但我仍然无法解决它。所以我将分享错误的堆栈跟踪希望得到你的帮助!

堆栈跟踪:

PM> Add-Migration 'Initial' -verbos Using project 'migration.presentence'. Using startup project 'e-commerce.migration'. Build started... Build succeeded. C:\Program Files\dotnet\dotnet.exe exec --depsfile C:\dev\backlogheros\e-commerce.migration\e-commerce.migration\bin\Debug\netcoreapp5.0\e-commerce.migration.deps.json --additionalprobingpath C:\Users\yousi.nuget\packages --runtimeconfig C:\dev\backlogheros\e-commerce.migration\e-commerce.migration\bin\Debug\netcoreapp5.0\e-commerce.migration.runtimeconfig.json C:\Users\yousi.nuget\packages\microsoft.entityframeworkcore.tools.0.1\tools\netcoreapp2.0\any\ef.dll migrations add Initial --json --verbose --no-color --prefix-output --assembly C:\dev\backlogheros\e-commerce.migration\e-commerce.migration\bin\Debug\netcoreapp5.0\migration.presentence.dll --startup-assembly C:\dev\backlogheros\e-commerce.migration\e-commerce.migration\bin\Debug\netcoreapp5.0\e-commerce.migration.dll --project-dir C:\dev\backlogheros\e-commerce.migration\migration.presentence
--language C# --working-dir C:\dev\backlogheros\e-commerce.migration --root-namespace migration.presentence Using assembly 'migration.presentence'. Using startup assembly 'e-commerce.migration'. Using application base 'C:\dev\backlogheros\e-commerce.migration\e-commerce.migration\bin\Debug\netcoreapp5.0'. Using working directory 'C:\dev\backlogheros\e-commerce.migration\e-commerce.migration'. Using root namespace 'migration.presentence'. Using project directory 'C:\dev\backlogheros\e-commerce.migration\migration.presentence'. Remaining arguments: . Finding DbContext classes... Finding IDesignTimeDbContextFactory implementations... Finding application service provider in assembly 'e-commerce.migration'... Finding Microsoft.Extensions.Hosting service provider... No static method 'CreateHostBuilder(string[])' was found on class 'Program'. No application service provider was found. Finding DbContext classes in the project... Found DbContext 'MigrationDbContext'. Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'MigrationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 ---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions' while attempting to activate 'migration.presentence.MigrationDbContext'.

at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)   
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)    
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)    
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13()
--- End of inner exception stack trace ---    
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13()
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)    
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)    
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)    
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)    
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

迁移工具必须实例化您的 DbContext 才能创建迁移。它有 3 种方法可以做到这一点:

  1. 由服务商解决
  2. 新()
  3. IDesignTimeDbContextFactory

由服务提供商解决

如果您希望迁移工具使用应用程序配置并解析来自服务提供商的 DbContext,则有多个要求,如第 https://go.microsoft.com/fwlink/?linkid=851728 页所述。

首先,您需要有一个在 DbContext 上采用 DbContextOptions 的构造函数。那部分没问题,只有在程序集中有多个 DbContext 时才需要指定 DbContextOptions<TContext>

其次,您必须使用主机构建器(ASP.NET、HTTP 或通用),该工具将在 class Program 中寻找 public static CreateHostBuilder(string[] args) 方法来访问它。这对您的基础架构 classes 有很多副作用,因为 IHostBuilder 将为您完成大部分 ServiceCollectionConfigurationBuilder 的工作。

此外,您的 DbContext 需要注册为单例,这可能是个问题。

Program.cs

internal class Program
{
    public static void LoadConfiguration(HostBuilderContext host, IConfigurationBuilder builder)
    {
        builder
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
            .AddEnvironmentVariables();
    }

    private static void ConfigureServices(HostBuilderContext host, IServiceCollection services)
    {
        services
            .AddDbContext<MigrationDbContext>(options =>
            {
                options.UseSqlServer(
                    host.Configuration.GetConnectionString("DEV_CS"), builder =>
                        builder.MigrationsAssembly("migration.presentence"));
            }, ServiceLifetime.Singleton)
            .AddHostedService<Startup>();
    }

    private static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(LoadConfiguration)
            .ConfigureServices(ConfigureServices);

    private static async Task Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }
}

为了使您的主机生成器 运行 您的自定义代码,您还需要将 Startup class 变成 IHostedService 例如 BackgroundService 例如。

Startup.cs

internal class Startup : BackgroundService
{
    private readonly MigrationDbContext context;

    public Startup(MigrationDbContext context)
    {
        this.context = context ?? throw new ArgumentNullException(nameof(context));
    }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        throw new NotImplementedException();
    }
}

新()

另一种选择是在 DbContext 上使用默认构造。但是,在那种情况下,您不能同时拥有默认构造函数和 DbContextOptions 构造函数。伤心。

IDesignTimeDbContextFactory

根据您的情况,最简单的解决方案可能是实施 IDesignTimeDbContextFactory<TContext>。如果找不到 IHostBuilder 并且 DbContext 使用 DbContextOptions 构造函数,工具将使用此 class。实现非常简单:

internal class MigrationDbContextFactory : IDesignTimeDbContextFactory<MigrationDbContext>
{
    public MigrationDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<MigrationDbContext>();
        optionsBuilder.UseSqlServer("Server=(localdb)\mssqllocaldb;Database=Test",
            b => b.MigrationsAssembly("migration.presentence"));
        return new MigrationDbContext(optionsBuilder.Options);
    }
}