.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/