How to use ASP.NET Detailed explanation of reading configuration file in core class library project

Time:2021-4-8

preface

Recently, a friend asked how to use. Net When reading the configuration file from the core class library, I was confused. I didn’t know how good it was. So I learned about the relevant content these two days before this article appeared. Normally, we have a file in the application directory appsettings.json File for the relevant configuration will be put in this JSON file, but if I build a class library project, for some configurations, it is better than For example, the key or other hard coded data should be put in the JSON file. Before. Net core, the configuration file is web.config And there are related classes to read the data on the node. Now it is a JSON file in the. Net core, so what should we do? This article arises at the historic moment.

The. Net core class library project reads the JSON configuration file

To add a JSON file to the application directory is to configure it 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 node of the configuration file as follows:


public void ConfigureServices(IServiceCollection services)
  {

   services.Configure<BlogViewModel>(Configuration.GetSection("JeffckySettings"));
   ......
   }

But if the project is in the class library, of course, we can also put the configuration value under the application appsettings.json However, in order not to make the JSON file look very bloated, and at the same time, we should put the configuration data in the class library for unified management, so we have to think of another solution, which can’t be established in the class library startup.cs Class, and then an example Let’s change configuration. I think it’s OK. I haven’t tried it. Isn’t there a very simple way? Can’t I use classes to read it like before. Net core web.config Do we just need to give the key to get the value? In other words, we should try to unify the management of configuration data through strong type configuration. Well, after all that, let’s go ahead. Let’s first review how to get the application path in. Net core.

. net core get application path

Before. Net 4. X, the path and name of the root directory of the current application can be obtained as follows


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

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


Directory.GetCurrentDirectory()

It is more concise to get the bin directory path in. Net core.


AppContext.BaseDirectory

Before. Net 4. X, get the application set name as follows:


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

In. Net core, you can obtain the following information through the following method:


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

The version is obtained as follows (. Net core is the same)


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

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

In the configurationbuilder class, add the following add method:

//
  //Abstract:
  //  Adds a new configuration source.
  //
  //Parameters:
  // 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 the JSON file name, the file path has been implemented through the setbasepath() method. All configurations are based on the iconfigurationbuilder interface, in which there is a jsonconfigurationsource class. The implementation is as follows:

//
 //Abstract:
 //  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.
  //
  //Parameters:
  // builder:
  //  The Microsoft.Extensions.Configuration.IConfigurationBuilder.
  //
  //Return result:
  //  A Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider
  public override IConfigurationProvider Build(IConfigurationBuilder builder);
 }

If we look at the parent class again, there is a way to add a JSON file path, as follows:

Therefore, we can see that the method of adding JSON file is not only implemented by extension method, but also implemented by directly instantiating jsonconfigurationsource, as follows:


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 any of the above JSON files. I found that to add a JSON file, you must set the directory where the JSON file is located, that is, you must first set the setbasepath method, otherwise the following error will be reported:

Let’s put a test JSON file in the current project( StudyEFCore.Data )The results are as follows:

Finally, read the JSON configuration file of the class library project and encapsulate it 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;
  }
 }

There is an unsolved problem from the above is how to get the path of the current class library project. I didn’t think of a good way. I don’t know what your opinions are after reading 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 results are as follows

We modify its class to configurationmanager, and then define its getappsettings method as a static method. Finally, does the following call satisfy the requirement of reading before. Net core web.config The problem of configuration data in. Ha ha ha:


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

summary

In this section, we explained in detail how to read the data in the JSON configuration in the. Net core class library project, but it is still a little insufficient. What’s your opinion?