How to read the configuration file details in the ASP. NET Core class library project, core class library

Source: Internet
Author: User

How to read the configuration file details in the ASP. NET Core class library project, core class library

Preface

Recently, a friend asked me how. the net core class library reads the configuration file, and I don't know how good it is. So I learned about the content these two days before this article came into being, normally, we have an ettings in the application directory. the json file stores related configurations in this json file, but if I create a class library project, some configurations such as keys or other hard-coded data are stored in the JSON file. before. net core, the configuration file is web. config and related classes are available to read data on the node. net core is a json file. What should we do? This article came into being.

. NET Core class library project reads the JSON configuration file

To add a JSON file to the application directory, perform the following Configuration:

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 node of the configuration file as follows:

public void ConfigureServices(IServiceCollection services)  {   services.Configure<BlogViewModel>(Configuration.GetSection("JeffckySettings"));   ......   }

However, if the project is in the class library, we can also place the configuration value in the deleettings under the application. json, but we should put the configuration data in the class library for unified management in order not to make the json file look very bloated, so we have to think about another solution, startup cannot be created in the class library. cs class, and then instantiate the Configuration. It should be okay if you think about it. I haven't tried it, isn't there a very simple way, isn't it like. net core Used classes to read web. config. Do we only need to give the key to get the value? In other words, it is our attempt to manage configuration data in a unified manner through forced configuration. Well, if we say so much, we will do it. First, let's review how. net core obtains the Application Path.

. NET Core obtains the Application Path

You can obtain the root directory path and name of the current application before. NET 4.x by using the following method:

var basePath = AppDomain.CurrentDomain.BaseDirectory;var appName = AppDomain.CurrentDomain.ApplicationIdentity.FullName;

Of course, you can also obtain the application root directory rather than the bin directory.

Directory.GetCurrentDirectory()

Obtain the bin directory path in. net core.

AppContext.BaseDirectory

Obtain the application Assembly name before. NET 4.x, as shown in the following figure:

Assembly.GetEntryAssembly().GetName().Name;

In. net core, obtain the following information:

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

Obtain the version as follows (. net core is also the same ):

Assembly.GetEntryAssembly().GetName().Version.ToString()

In the class library project, we use a strong type configuration to read configuration file data. First, we need to download the following extension.

In the ConfigurationBuilder class, Add a method as follows:

//// Summary: // 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. All configurations are based on the IConfigurationBuilder interface. There is a JsonConfigurationSource class, which is implemented as follows:

//// Summary: // Represents a JSON file as an Microsoft. extensions. configuration. IConfigurationSource. public class JsonConfigurationSource: FileConfigurationSource {public JsonConfigurationSource (); // Abstract: // Builds the Microsoft. extensions. configuration. json. jsonConfigurationProvider // for this source. //// parameter: // builder: // The Microsoft. extensions. configuration. IConfigurationBuilder. //// return result: // A Microsoft. extensions. configuration. json. jsonConfigurationProvider public override IConfigurationProvider Build (IConfigurationBuilder builder );}

Let's look at its parent class as a method to add a JSON file path, as shown below:

Therefore, we can see from here that the method for adding a JSON file is not only implemented through the extension method, but also directly instantiated JsonConfigurationSource for implementation, as shown below:

IConfiguration config = new ConfigurationBuilder()    .SetBasePath(currentClassDir)    .AddJsonFile("appsettings.json", false, true)    .Add(new JsonConfigurationSource { Path = "appsettings.json", Optional = false, ReloadOnChange = true })    .Build();

You can add a JSON File above. I found that you must set the directory where the JSON file is to be added. You must first set the SetBasePath method. Otherwise, the following error will be reported:

We have a test JSON file in the current project (StudyEFCore. Data) as follows:

Finally, the JSON configuration file of the class library project is read and encapsulated as follows:

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

The previous unsolved problem is how to get the path of the current class library project. I didn't think of a good method. I don't know what you think of in this article. The short call is as follows:

 var config = new JsonConfigurationHelper();   var person = config.GetAppSettings<Person>("JeffckySettings");   var name = person.Name;   var age = person.Age;

The result is as follows:

We changed its class to ConfigurationManager, and defined its getreceivetaskmethod as a static method. Finally, the following call satisfies the problem of reading web. config configuration data before. net core. Hahaha:

var person = ConfigurationManager.GetAppSettings<Person>("JeffckySettings");

Summary

This section describes in detail how to read the data in the JSON configuration in the. net core class library project, but it is still a bit insufficient. What are your comments?

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.