本文介绍了如何将连接字符串从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:***"]);
            });

这是上下文构造函数(仅此,不是默认的,因为如果我编写默认的,则不会) t从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 framework 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")));

然后,当您的存储库/服务/任何类需要使用Context时,它将注入到

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:17