gpt4 book ai didi

c# - 播种 ServiceStack 数据库

转载 作者:行者123 更新时间:2023-11-30 23:01:19 28 4
gpt4 key购买 nike

在 .net 核心项目中,我像这样在 Program.cs 文件中播种:

var host = BuildWebHost(args);

using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<ApplicationDbContext>();

//.. do seeding
}
catch
{

}
}

host.Run();

在服务堆栈中,服务是否在同一个地方注册?我尝试了下面的代码,但是 var db = context.OpenDbConnection() 抛出服务未注册的异常:

No service for type 'ServiceStack.Data.IDbConnectionFactory' has been registered.

我是这样调用它的:

var host = BuildWebHost(args);

using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<IDbConnectionFactory>();


using (var db = context.OpenDbConnection())
{
if(!db.Select<Register>(x => x.Email == "test@example").Any())
{
db.Insert(new Register
{
Email = "test@example.com",
Password = "1234"
});
}

}

//.. do seeding
}
catch
{

}

}

host.Run();

这就是我在 Startup.cs Configure() 中注册它的方式

container.Register<IDbConnectionFactory>(c =>
new OrmLiteConnectionFactory(_sqliteFileDb, SqliteDialect.Provider));

container.Register<IAuthRepository>(c =>
new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));

container.Resolve<IAuthRepository>().InitSchema();

注册和检索数据库上下文的正确方法是什么?

最佳答案

您正在寻找 .NET Core 的 IOC 中的依赖项,但依赖项 registered in ServiceStack's IOC is only visible to ServiceStack .

通常您会在注册依赖项后播种数据,因为它们都只在启动时注册和配置一次,例如:

container.Register<IDbConnectionFactory>(c =>
new OrmLiteConnectionFactory(_sqliteFileDb, SqliteDialect.Provider));

using (var db = container.Resolve<IDbConnectionFactory>().Open())
{
SeedData(db);
}

否则,您可以通过以下方式访问 ServiceStack 的 IOC 中的依赖项:

var dbFactory = HostContext.TryResolve<IDbConnectionFactory>();

using (var db = dbFactory.Open())
{
}

关于c# - 播种 ServiceStack 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51087585/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com