How to implement read configuration file in ASP. NET Core Class Library project

Source: Internet
Author: User
This article mainly introduces you about how to read the configuration file in the ASP. NET Core Class library project, this is a friend raised a question, the article through the example code introduced by the very detailed, to everyone's study or work has a certain reference learning value, The friends who need to have a look along with the small series.

Objective

Recently a friend asked how to read the configuration file in the. NET Core class library, at that time blindfolded, this mention of how good, I actually do not know, so these two days to understand the relevant content only this article appeared, Normally we have a Appsettings.json file in the application directory for the relevant configuration will be placed in this JSON file, but if I set up a class library project, for some configuration such as keys or other hard-coded data in the JSON file, in the. Net Before the core configuration file is Web. config and has related classes to read the data on the node, now in. NET core is a JSON file, so what do we do? This article was born.

. NET Core Class Library project reading JSON configuration file

Adding a JSON file under the application directory is configured as follows:


var builder = new Configurationbuilder ()    . Setbasepath (env. Contentrootpath)    . Addjsonfile ("Appsettings.json", Optional:true, Reloadonchange:true)    . Addjsonfile ($ "appsettings.{ Env. Environmentname}.json ", Optional:true)    . Addenvironmentvariables ();    Configuration = Builder. Build ();

Then read the configuration file node, as follows:


public void Configureservices (iservicecollection services)  {   services. Configure<blogviewmodel> (Configuration.getsection ("jeffckysettings"));   ......   }

But what if the project is in the class library, Of course, we can also put the configuration values in the application under the Appsettings.json, but in order not to make its JSON file looks very bloated and in the class library configuration data we should put in the class library to unified management, so we have to think of a solution, we can not build Startup.cs class in the class library, and then to Instantiation of the configuration bar, so think should also be able, I have not tried, there is no very simple way, can not be like. NET core with a class to read the Web. config we just need to give the key to get the value? or by using strongly typed configurations to manage configuration data uniformly, this should be the direction we try. Well, with so much to say, we'll do it. Let's start by reviewing how to get the application path in. NET Core.

. NET Core Get application path

Getting the current application root path and name before. NET 4.X can be obtained by following


var basepath = Appdomain.currentdomain.basedirectory;var AppName = AppDomain.CurrentDomain.ApplicationIdentity.FullName;

Of course, you can get the application root directory instead of the bin directory by following


Directory.GetCurrentDirectory ()

Getting the Bin directory path in. NET core is more concise with the following.


Appcontext.basedirectory

Get the application set name before. NET 4.X by following these:


Assembly.getentryassembly (). GetName (). Name;

In. NET core, get the following:


var name = typeof (T). GetTypeInfo (). Assembly.getname (). Name;

Version is obtained by using the following (. NET core also):


Assembly.getentryassembly (). GetName (). Version.tostring ()

In the Class library project we use the strongly typed configuration to implement the read file data, we first need to download the following extension.

The following Add method is added to the Configurationbuilder class:


  //Abstract:  //  Adds a new configuration source.  //  parameter:  //Source://The  configuration source to add.  //Return Result:  //The  same Microsoft.Extensions.Configuration.IConfigurationBuilder.  Public Iconfigurationbuilder Add (Iconfigurationsource source);

For the Addjsonfile extension method to add a JSON file name, the file path has been implemented through the Setbasepath () method, and all configurations are based on the Iconfigurationbuilder interface. There is a Jsonconfigurationsource class, which is implemented as follows:


Abstract://  represents a JSON file as an Microsoft.Extensions.Configuration.IConfigurationSource. public class Jsonco Nfigurationsource:fileconfigurationsource {public  jsonconfigurationsource ();  //Abstract:  //  Builds the Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider  //  For this source.  //Parameters:  //Builder:/  /The  Microsoft.Extensions.Configuration.IConfigurationBuilder.  //Return Result:  //  A Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider  Public Override Iconfigurationprovider Build (Iconfigurationbuilder builder); }

Let's look at the parent class. There is a way to add a JSON file path, as follows:

So we can see from here that the way to add a JSON file, in addition to the extension method to implement a direct instantiation of the jsonconfigurationsource to achieve, as follows:


iconfiguration config = new Configurationbuilder ()    . Setbasepath (Currentclassdir)    . Addjsonfile ("Appsettings.json", False, True)    . ADD (new Jsonconfigurationsource {Path = "Appsettings.json", Optional = False, Reloadonchange = true})    . Build ();

Add the JSON file above, I found that the add JSON file must be set the JSON file in the same directory that must first set the Setbasepath method, otherwise the following error will be reported:

Let's get a test. The JSON file is placed in the current project (Studyefcore.data) as follows:

The final reading of the Class Library project JSON configuration file, encapsulating it, looks like this:


public class Jsonconfigurationhelper {public  T getappsettings<t> (string key) where T:class, new ()  {   var baseDir = appcontext.basedirectory;   var indexsrc = basedir.indexof ("src");   var subtosrc = basedir.substring (0, indexsrc);   var currentclassdir = subtosrc + "src" + Path.directoryseparatorchar + "Stutdyefcore.data";   iconfiguration config = new Configurationbuilder ()    . Setbasepath (Currentclassdir)    . ADD (new Jsonconfigurationsource {Path = "Appsettings.json", Optional = False, Reloadonchange = true})    . Build ();   var appconfig = new Servicecollection ()    . AddOptions ()    . configure<t> (config. GetSection (key))    . Buildserviceprovider ()    . Getservice<ioptions<t>> ()    . Value;   return appconfig;  } }

From the top there is an unresolved problem is how to get the current class library project path, did not think of a good way, do not know what you have to see this article. The short call is as follows:


var config = new Jsonconfigurationhelper ();   var person = config. Getappsettings<person> ("jeffckysettings");   var name = person. Name;   var = person. Age;

The results are as follows:

We modify its class to ConfigurationManager and then define its Getappsettings method as a static method, and finally the following call does not satisfy the problem of reading the configuration data in Web. config before. NET core. HAHAHA:


var person = configurationmanager.getappsettings<person> ("jeffckysettings");

Summarize

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.