This article mainly introduces you to the relevant information on how to read the configuration file in the ASP.NET Core class library project. This is a question raised by a friend. The article introduces it in detail through the sample code. It will be helpful to everyone. It has certain reference and learning value when studying or working. Friends who need it can follow the editor to take a look.
Preface
Recently, a friend asked how to read the configuration file in the .net core class library. At that time, I was confused. What to ask? How great, I didn’t know, so I learned about the relevant content in the past two days and this article appeared. Normally, we have an appsettings.json file in the application directory, and the relevant configurations will be placed in this json file. But if I build a class library project, some configurations such as keys or other data that need to be hard-coded are placed in a JSON file. Before .net core, the configuration file is web.config and there are related classes to read the data on the node. Data is now a json file in .net core, so what should we do? This article came into being.
.NET Core class library project reads JSON configuration file
To add a JSON file in 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")); ...... }
But if the project is in a class library, Of course, we can also put the configuration values in appsettings.json under the application, but in order to prevent the json file from looking very bloated, we should put the configuration data in the class library for unified management. So we have to think of another solution. We can't create the startup.cs class in the class library and then instantiate the Configuration. Thinking about it this way, it should be possible. I haven't tried it. Isn't there a simple way? Isn't it possible? Like before using classes in .net core to read web.config, do we only need to give the key and get the value? In other words, unified management of configuration data through strong type configuration should be the direction we try. Okay, having said all that, let’s get started. Let's first review how to obtain the application path in .net core.
.NET Core gets the application path
Getting the current application root path and name before .NET 4.X can be done as follows Get
var basePath = AppDomain.CurrentDomain.BaseDirectory; var appName = AppDomain.CurrentDomain.ApplicationIdentity.FullName;
Of course, you can also get the application root directory instead of getting the bin directory as follows
Directory.GetCurrentDirectory()
In It is more concise to obtain the bin directory path in .net core as follows.
AppContext.BaseDirectory
Before .NET 4.X Obtaining the application set name was obtained by:
Assembly.GetEntryAssembly().GetName().Name;
In In .net core, you can obtain it as follows:
var name = typeof(T).GetTypeInfo().Assembly.GetName().Name;
. The version can be obtained as follows (the same is true for .net core):
Assembly.GetEntryAssembly().GetName().Version.ToString()
In the class library project, we use strong type configuration to read configuration file data. We first need to download the following extension.
In the ConfigurationBuilder class, add the following Add method:
// // 摘要: // Adds a new configuration source. // // 参数: // source: // The configuration source to add. // // 返回结果: // 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, which has a JsonConfigurationSource class, which is implemented as follows:
// // 摘要: // Represents a JSON file as an Microsoft.Extensions.Configuration.IConfigurationSource. public class JsonConfigurationSource : FileConfigurationSource { public JsonConfigurationSource(); // // 摘要: // Builds the Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider // for this source. // // 参数: // builder: // The Microsoft.Extensions.Configuration.IConfigurationBuilder. // // 返回结果: // A Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider public override IConfigurationProvider Build(IConfigurationBuilder builder); }
Let’s take a look at it The parent class has a method to add a JSON file path, as follows:
So we can see from here that in addition to the extension method, there are other ways to add a JSON file. Directly instantiate JsonConfigurationSource to achieve this, as follows:
IConfiguration config = new ConfigurationBuilder() .SetBasePath(currentClassDir) .AddJsonFile("appsettings.json", false, true) .Add(new JsonConfigurationSource { Path = "appsettings.json", Optional = false, ReloadOnChange = true }) .Build();
All of the above can be added to the JSON file. I found that adding a JSON file must set the directory where the JSON file is located, that is, SetBasePath must be set first. method, otherwise the following error will be reported:
Let’s create a test JSON file and place it in the current project (StudyEFCore.Data) as follows:
Finally read the JSON configuration file of the class library project and encapsulate it to look like the following:
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 one unresolved issue from the above The problem is how to get the path of the current class library project. I haven't thought of a good way. I wonder if you have any advice 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 result is as follows:
我们将其类修改为ConfigurationManager,然后将其GetAppSettings方法定义为静态方法,最后如下调用是不是满足了在.net core之前读取web.config中配置数据的问题。哈哈哈:
var person = ConfigurationManager.GetAppSettings<Person>("JeffckySettings");
总结
The above is the detailed content of Detailed explanation of how to read configuration files in ASP.NET Core class library project. For more information, please follow other related articles on the PHP Chinese website!