播种ServiceStack数据库

时间:2018-06-28 16:24:34

标签: c# asp.net-core servicestack ormlite-servicestack

在.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()抛出未注册服务的异常:

  

没有注册类型为'ServiceStack.Data.IDbConnectionFactory'的服务。

这就是我所说的:

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();

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

1 个答案:

答案 0 :(得分:2)

您要在.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())
{
}