从控制器配置连接字符串(ASP.NET Core MVC 2.1)

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

我想从控制器配置连接字符串,但我找不到任何功能。

我有:

public class tstController : Controller
{
    private readonly contextTst _context;

    public tstController(contextTst context)
    {
        _context = context;
        _context.Database.**????**
    }
}

这是可能的?

非常感谢!

c# asp.net-core asp.net-core-mvc
2个回答
1
投票

鉴于您要在构造函数中设置备用连接字符串,建议它是已知值。

要解决的问题是如何用DI做到这一点。第一个提示是脚手架上下文时生成的代码:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
//#warning To protect potentially sensitive information in your
// connection string, you should move it out of source code.
// See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
        optionsBuilder.UseSqlServer("Server=.\\SQLEXPRESS;Database=MyDb;Trusted_Connection=True;");
    }
}

这意味着您可以使用默认配置(optionsBuilder.IsConfigured),在启动时设置值。但也使用替代建筑。

代码将如下所示:

public partial class MyContext : DbContext
{
    private readonly string _connectionString;

    public MyContext(DbContextOptions<MyContext> options)
        : base(options)
    {
    }

    public MyContext(IOptions<DbConnectionInfo> dbConnectionInfo)
    {
        _connectionString = dbConnectionInfo.Value.MyContext;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(_connectionString);
        }
    }
}

辅助类看起来像这样:

public class DbConnectionInfo
{
    public string MyContext { get; set; }
}

示例appsettings.json:

"ConnectionStrings": {
    "MyContext": "Server=.\\SQLEXPRESS;Database=MyDb;Trusted_Connection=True;"
  },

并在启动时注册:

services.Configure<DbConnectionInfo>(settings => configuration.GetSection("ConnectionStrings").Bind(settings));
services.AddScoped<MyContext>();

如果您不想从配置中读取连接字符串,而是根据中间件(例如每个租户)设置它,那么您可以使用相同的方法。只需在构造上下文之前更新该值。


更新:

使用依赖项注入时,您不会自己构造对象,而是将注册的对象/服务作为参数传递。 DI将确定需要以什么顺序创建哪些对象。以相同的方式,物体将在使用后通过DI处理。

控制器“知道”上下文的事实是因为DI将其自动添加为参数。上下文“知道”DbConnectionInfo的事实是因为它已注册到DI。

如果要更改DbConnectionInfo,则需要以适当的方式添加它。在你的情况下,你可以做这样的事情:

// Added as part of the example
services.AddHttpContextAccessor();
// Replace registration with this line:
services.AddScoped<DbConnectionInfo>();
// Register the DbContext
services.AddScoped<MyContext>();

该类的替代版本是:

public class DbConnectionInfo
{
    public string MyContext { get; set; }

    // Example injecting IHttpContextAccessor
    // On creating this class DI will inject 
    // the HttpContextAccessor as parameter
    public DbConnectionInfo(IHttpContextAccessor httpContextAccessor)
    {
        // Access the current request
        var request = httpContextAccessor.HttpContext.Request;

        // Access the current user (if authenticated)
        var user = httpContextAccessor.HttpContext.User;

        // Now you could get a value from a header, claim,
        // querystring or path and use that to set the value:

        MyContext = "";
    }
 }

在DbContext中进行了一些小改动,在这种情况下我们不使用IOptions:

public partial class MyContext : DbContext
{
    private readonly string _connectionString;

    public MyContext(DbConnectionInfo dbConnectionInfo)
    {
        _connectionString = dbConnectionInfo.MyContext;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder     optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(_connectionString);
        }
    }
}

现在,在每个请求上,将在创建MyContext之前设置该值。


1
投票

您应该仅在启动期间注册DbContext。

只有你应该指定连接字符串。

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionString")));

    services.AddMvc();
}

如果你是using dependency injection (from MSDN),这非常重要:

实体框架上下文应使用范围生存期将实体框架上下文添加到服务容器中。注册数据库上下文时,通过调用AddDbContext方法自动处理。使用数据库上下文的服务也应使用作用域生存期。

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.