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

我想从控制器配置连接字符串,但我找不到任何功能来执行此操作。


我有:


public class tstController : Controller

{

    private readonly contextTst _context;


    public tstController(contextTst context)

    {

        _context = context;

        _context.Database.**????**

    }

}

有可能?


Helenr
浏览 75回答 2
2回答

青春有我

鉴于您希望在构造函数中设置备用连接字符串,则表明它是一个已知值。要解决的问题是如何用DI做到这一点。第一个提示是在基架上下文时生成的代码:protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){&nbsp; &nbsp; if (!optionsBuilder.IsConfigured)&nbsp; &nbsp; {//#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.&nbsp; &nbsp; &nbsp; &nbsp; optionsBuilder.UseSqlServer("Server=.\\SQLEXPRESS;Database=MyDb;Trusted_Connection=True;");&nbsp; &nbsp; }}这意味着您可以使用默认配置(optionsBuilder.IsConfigured),在启动时设置该值。但也要在建筑上使用替代方案。然后,代码将如下所示:public partial class MyContext : DbContext{&nbsp; &nbsp; private readonly string _connectionString;&nbsp; &nbsp; public MyContext(DbContextOptions<MyContext> options)&nbsp; &nbsp; &nbsp; &nbsp; : base(options)&nbsp; &nbsp; {&nbsp; &nbsp; }&nbsp; &nbsp; public MyContext(IOptions<DbConnectionInfo> dbConnectionInfo)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _connectionString = dbConnectionInfo.Value.MyContext;&nbsp; &nbsp; }&nbsp; &nbsp; protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (!optionsBuilder.IsConfigured)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; optionsBuilder.UseSqlServer(_connectionString);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}其中,帮助程序类如下所示:public class DbConnectionInfo{&nbsp; &nbsp; public string MyContext { get; set; }}示例 appsettings.json:"ConnectionStrings": {&nbsp; &nbsp; "MyContext": "Server=.\\SQLEXPRESS;Database=MyDb;Trusted_Connection=True;"&nbsp; },并在启动时注册两者:services.Configure<DbConnectionInfo>(settings => configuration.GetSection("ConnectionStrings").Bind(settings));services.AddScoped<MyContext>();如果您不想从配置中读取连接字符串,而是根据中间件(例如,每个租户)进行设置,则可以使用相同的方法。只需在构造上下文之前更新值即可。更新:使用依赖注入,您不需要自己构造对象,而是将已注册的对象/服务作为参数传递。DI 将确定需要以什么顺序创建哪些对象。以同样的方式,对象将在使用后由DI处理。控制器“知道”上下文的事实是,DI 会自动将其添加为参数。上下文“知道”DbConnectionInfo 的事实是因为它已注册到 DI。如果要更改 DbConnectionInfo,则需要以正确的方式添加它。在你的情况下,你可以做这样的事情:// Added as part of the exampleservices.AddHttpContextAccessor();// Replace registration with this line:services.AddScoped<DbConnectionInfo>();// Register the DbContextservices.AddScoped<MyContext>();其中类的替代版本是:public class DbConnectionInfo{&nbsp; &nbsp; public string MyContext { get; set; }&nbsp; &nbsp; // Example injecting IHttpContextAccessor&nbsp; &nbsp; // On creating this class DI will inject&nbsp;&nbsp; &nbsp; // the HttpContextAccessor as parameter&nbsp; &nbsp; public DbConnectionInfo(IHttpContextAccessor httpContextAccessor)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Access the current request&nbsp; &nbsp; &nbsp; &nbsp; var request = httpContextAccessor.HttpContext.Request;&nbsp; &nbsp; &nbsp; &nbsp; // Access the current user (if authenticated)&nbsp; &nbsp; &nbsp; &nbsp; var user = httpContextAccessor.HttpContext.User;&nbsp; &nbsp; &nbsp; &nbsp; // Now you could get a value from a header, claim,&nbsp; &nbsp; &nbsp; &nbsp; // querystring or path and use that to set the value:&nbsp; &nbsp; &nbsp; &nbsp; MyContext = "";&nbsp; &nbsp; }&nbsp;}在 DbContext 中,稍作更改,在这种情况下,我们不会使用 IOptions:public partial class MyContext : DbContext{&nbsp; &nbsp; private readonly string _connectionString;&nbsp; &nbsp; public MyContext(DbConnectionInfo dbConnectionInfo)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _connectionString = dbConnectionInfo.MyContext;&nbsp; &nbsp; }&nbsp; &nbsp; protected override void OnConfiguring(DbContextOptionsBuilder&nbsp; &nbsp; &nbsp;optionsBuilder)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (!optionsBuilder.IsConfigured)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; optionsBuilder.UseSqlServer(_connectionString);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}现在,对于每个请求,将在创建 MyContext 之前设置该值。

慕标5832272

您应仅在启动期间注册 DbContext。只有您应指定连接字符串。public void ConfigureServices(IServiceCollection services){&nbsp; &nbsp; services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnectionString")));&nbsp; &nbsp; services.AddMvc();}如果您使用的是依赖关系注入(来自 MSDN),这一点非常重要:实体框架上下文应使用作用域生存期将实体框架上下文添加到服务容器。这是在注册数据库上下文时通过调用 AddDbContext 方法自动处理的。使用数据库上下文的服务也应使用作用域内的生存期。希望这有帮助。
打开App,查看更多内容
随时随地看视频慕课网APP