如何将连接字符串从 appsettings.[name].json 传递到 .NET Core 中的 DbContext? [英] How to pass connection string from appsettings.[name].json to DbContext in .NET Core?

查看:17
本文介绍了如何将连接字符串从 appsettings.[name].json 传递到 .NET Core 中的 DbContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .net 核心应用程序.我在 appsettings.json 文件中写入我的连接字符串.但是,现在,我想为我的上下文获取该连接字符串.怎么做?

I have a .net core app. I write my connection string in appsettings.json file. But, now, I want to get that connection string for my context. How to do that?

在 .net framework 4.6 中我使用了这个:

In .net framework 4.6 I used this:

ConfigurationManager.ConnectionStrings["ConnStrName"].ConnectionString;

我有这样的 appsettings.Development.json(*** 可以是任何名称):

I have appsettings.Development.json like this (*** could be any name):

"ConnectionStrings": {
    "***": "Server=***;Database=****;Trusted_Connection=True;MultipleActiveResultSets=true;"
  }

我添加了服务:

services.AddTransient<MyContext>(provider =>
            {
                return new MyContext(configuration["ConnectionStrings:***"]);
            });

这是上下文构造函数(只有这个,不是默认的,因为如果我写一个默认的,不会从json文件中获取我的连接字符串):

and this is context constructor (ONLY THIS, not default ones because if I write a default one doesn't take my connection string from json file):

public MyContext(string connectionString)
        : base(connectionString)
    {
        try
        {
            this.Database.Log = (s) => System.Diagnostics.Debug.Write(s);
        }
        catch (Exception e)
        {
            //CurrentLogger.Log.Error(e);
        }
    }

此后,我在运行 Enable-Migration 命令后出现此错误

After that I've got this error after I run Enable-Migration command

目标上下文MyContext"是不可构建的.添加默认构造函数或提供 IDbContextFactory 的实现.

如果我能以某种方式从这里的 json 获取连接字符串:

If somehow I could get connection string from json here:

一切都会好的.但如果可能的话,我想在 .NET CORE 中用一行来做到这一点,就像在 .net 框架中一样:

all will be good. But I want to do that with a single line in .NET CORE if it would be possible, like in .net framework: with this:

ConfigurationManager.ConnectionStrings["ConnStrName"].ConnectionString;

.net 框架 4.6

推荐答案

.NET Core 中的一切都是围绕依赖注入构建的,而不是使用 ConfigurationManager 之类的静态实例.

Everything in .NET Core is built around dependency injection instead of using static instances of things like ConfigurationManager.

您可以通过几种不同的方式来做到这一点.

You could do this in a couple different ways.

首先将使用以下内容在 Startup.cs ConfigureServices 中注册您的 DbContext:

First would be registering your DbContext in Startup.cs ConfigureServices using something like this:

services.AddDbContext<MyContext>(context => context.UseSqlServer(Configuration.GetConnectionString("name")));

然后当你的存储库/服务/任何类需要使用上下文时,它将使用构造函数注入到类中以便你可以使用它.

Then when your repository/service/whatever class needs to use the Context, it will be injected into the class using the constructor so you can use it.

public class SomeClass(MyContext context)
{

}

或者,如果您不想那样做,也可以将IConfiguration"注入到 DbContext 的构造函数中,然后使用 IConfiguration 来获取连接字符串:

Or, if you don't want to do it that way, you can also inject 'IConfiguration' into the constructor of your DbContext and then do use the IConfiguration to get the connection string:

public class SomeClass(IConfiguration config)
{
    config.GetConnectionString("name")
}

这篇关于如何将连接字符串从 appsettings.[name].json 传递到 .NET Core 中的 DbContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆