DotNet Core在启动运行后设置连接字符串

问题描述 投票:2回答:2

我有一个有两个数据库连接的Visual Studio解决方案。第一个是包含用户名密码和数据库的目录。第二个是用户数据。我可以在“ConfigureServices”中设置目录数据库的连接,那很好。一旦用户尝试登录并成功,我就可以知道用户将连接到的数据库。

我的问题是,如何在启动运行后创建服务..如何在正常的操作过程中使用连接字符串添加DBcontext。如果您在启动时知道连接字符串,那么从我的搜索中就可以了。

var connection = @"Server=(localdb)\mssqllocaldb;Database=JobsLedgerDB;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));

但是如果我在启动时没有连接字符串...当我最终拥有连接字符串时,如何在项目启动并运行后添加服务?

c# asp.net-core entity-framework-core
2个回答
0
投票

您可以在应用程序的每个类中实例化DbContext。

检查文档:Configuring a DbContext

var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");

using (var context = new BloggingContext(optionsBuilder.Options))
{
  // do stuff
}

对于SQL连接

var connection = @"Server=(localdb)\mssqllocaldb;Database=JobsLedgerDB;Trusted_Connection=True;ConnectRetryCount=0";
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlServer(connection);

using (var context = new BloggingContext(optionsBuilder.Options))
{
  // do stuff
}

2
投票

Tolbxela的另一个答案建议在需要时根据需要创建新的上下文,但如果您想使用依赖注入则不起作用。相反,您应该使用ConfigureServices扩展方法在Startup类的AddDbContext方法中提供这样的工厂,正如Camilo在该答案的评论中所述:

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        ...

        services.AddDbContext<BloggingContext>(options =>
        {
            var customerId = serviceProvider.GetService<IHttpContextAccessor>().HttpContext?.User?.FindFirst("customerId")?.Value;
            var connectionString = 
                $"bla blah blah ;Initial Catalog={customerId}";
            options.UseSqlServer(connectionString);

在此示例中,初始目录设置为声明“customerId”的值。 (FindFirst是我自己编写的自定义扩展方法)。这个例子只是为了让你了解这种方法。

然后,您可以像往常一样注入上下文:

public class MyController : Controller
{

    public MyController(BloggingContext context)
    {
        ...
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.