Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

c# - read connectionstring outside startup from appsetting.json in vNext

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

Static Class Method:

        /// <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);
        }

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

It is possible?

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;
    }

Thanks!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1.ConnectionString in appsetting.json

enter image description here

  1. Creating Singleton Instance of Configuration in Startup.cs class

enter image description here

  1. Reading Values from Configuration Instance Using Dependency Injection [Constructor injection ]

enter image description here

  1. Finally Output

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...