在vNext中从appsetting.json读取启动后的连接字符串

编程入门 行业动态 更新时间:2024-10-25 07:17:58
本文介绍了在vNext中从appsetting.json读取启动后的连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个项目课程(Nuget软件包).我需要在没有构造函数的静态类中读取与MongoDB的连接字符串.

I have a project class (Nuget Package). I need to read in a static class without constructor my connections string to MongoDB.

静态类方法:

/// <summary> /// The default key MongoRepository will look for in the appsettings.json /// </summary> private const string DefaultConnectionstringName = "Data:MongoDB:MongoServerSettings"; /// <summary> /// Retrieves the default connectionstring from appsettings.json /// </summary> /// <returns>Returns the default connectionstring from the App.config or Web.config file.</returns> public static string GetDefaultConnectionString() { var config = new Configuration(); return config.Get<string>(DefaultConnectionstringName); }

我总是为空...如何在不使用DI的情况下获取Startup.cs之外的值?

I have always null... How can I obtain the value outside the Startup.cs without using DI?

有可能吗?

在我的旧代码中,我可以做类似的事情:

In my old code I could do something like that:

/// <summary> /// Retrieves the default connectionstring from the App.config or Web.config file. /// </summary> /// <returns>Returns the default connectionstring from the App.config or Web.config file.</returns> public static string GetDefaultConnectionString() { return ConfigurationManager.ConnectionStrings[DefaultConnectionstringName].ConnectionString; }

谢谢!

推荐答案

在启动过程中,应将连接字符串保存到Startup

Inside your startup, you should save the connection string to a static property on Startup

public class Startup { public static string ConnectionString { get; private set; } public Startup(IHostingEnvironment env) { // Set up configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddUserSecrets(); if (env.IsDevelopment()) { // For more details on using the user secret store see go.microsoft/fwlink/?LinkID=532709 builder.AddUserSecrets(); } builder.AddEnvironmentVariables(); Configuration = builder.Build(); ConnectionString = Configuration.Get<string>("Data:MongoDB:MongoServerSettings"); } // ... }

那么您应该可以从任何地方访问它:

Then you should be able to access it from wherever:

public static string GetDefaultConnectionString() { return Startup.ConnectionString; }

更多推荐

在vNext中从appsetting.json读取启动后的连接字符串

本文发布于:2023-11-14 02:52:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586023.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   vNext   appsetting   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!