c# - 使用简单注入(inject)器的更新数据库,没有 services.AddDbContext<>()

标签 c# asp.net-core entity-framework-core entity-framework-5 simple-injector

.NET Core 3.1、EF Core 5.0 预览版 6。
我正在使用 Simple Injector 5.0注册IMyContextFactory (我没有使用 services.AddDbContext<>() )。
我的 MyContext将所有构造函数设置为私有(private),因为我使用没有tenantId 的ContextFactory,有时在一个请求中使用几个不同的tenantId,所以我确保每个人都会使用IMyContextFactory注入(inject)代替 MyContext并防止创建 new MyContext()在 Controller 等
但是怎么办Update-Database ?

  • 当我做 Update-Database我总是有错误Login failed for user ''. ,但我可以毫无问题地从我的 WebAPI 项目运行并连接到数据库(我的 ConnectionString 很好)。
  • 我能够在运行时应用迁移,但我必须添加 services.AddDbContext<MyContext>() , 为 MyContext 创建构造函数公开并从 scope.ServiceProvider.GetRequiredService<MyContext>() 获取此上下文在 Program.cs 中,因为我的 IMyContextFactory不在里面 ServiceProvider . (通过 https://docs.microsoft.com/pl-pl/ef/core/managing-schemas/migrations/applying?tabs=vs#apply-migrations-at-runtime )

  • 如何仅使用 Simple Injector 实现这一目标?

    最佳答案

    解决方案是将 ConnectionString 添加到您的 IDesignTimeDbContextFactory执行:

    // Fix for "Unable to create an object of type 'MyContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728" error while creating migration
    public class MyContextDesignFactory : IDesignTimeDbContextFactory<MyContext>
    {
        private string _appsettingsPath = "./../Path/To/ProjectWithAppsettingsJSON";
    
        public MyContext CreateDbContext(string[] args)
        {
            // In 90% we don't have ASPNETCORE_ENVIRONMENT here, so set fallback to Development
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
    
            var config = new ConfigurationBuilder()
                .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), _appsettingsPath))
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{environment}.json", optional: true)
                .Build();
    
            Console.WriteLine($"Default ConnectionString comes from appsettings file.{Environment.NewLine}You can override it by using `dotnet ef database update --connection MyConnectionString`");
    
            // Use ConnectionString from appsettings inside WebAPI to fix `Update-Database` command from Package Manager Console
            // We still can override ConnectionString by `dotnet ef database update --connection MyConnectionString`
            var optionsBuilder = new DbContextOptionsBuilder<MyContext>()
                .UseSqlServer(config["ConnectionString"]);
    
            return MyContext.MyContextFactory.GetMyContext(optionsBuilder.Options);
        }
    }
    

    关于c# - 使用简单注入(inject)器的更新数据库,没有 services.AddDbContext<>(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63129261/

    相关文章:

    c# - 分配非托管资源的位置

    c# - 在 Windows Phone 项目中将值从一个页面传递到另一个页面

    entity-framework - asp.net Core 2 中的 AddOrUpdate() 方法

    azure - 通过 EF Core 自动创建时的默认 Azure SQL DB 定价

    asp.net-core - EF Core 迁移错误 : "Unable to create an object of type ' ApplicationContext'"

    时间:2019-04-10 标签:c#closureslambda

    c# - 在返回空 200 响应的 WebAPI 操作方法中抛出 HttpResponseException

    c# - 当我们在 Entity Framework Core 中拥有主键时,我们是否应该始终使用 .Find() 而不是 .FirstOrDefault() ?

    c# - 迁移到 ASP.NET Core RC2 后集成测试中断

    c# - 添加数据库迁移时指定应用程序设置