问题描述
要访问类库中的应用键,是否需要在每个需要访问AppKey的类库和类中执行以下代码?
To access App Keys in a class library, do we need to do the following code in every class library and class where we need to access a AppKey?
public static IConfigurationRoot Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
这就是我在,但这看起来非常多余。
This is what I found in Microsoft docs, but this looks very redundant.
以下项目中的启动类
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework().AddEntityFrameworkSqlServer()
.AddDbContext<DbContext>(options =>
options.UseSqlServer(Configuration["Data:MyDb:ConnectionString"]));
}
}
然后我应该如何注入此 IConfigurationRoot 。我是否必须在每个类库中重复此Startup类?为什么这不是.NET Core Framework的一部分?
Then how should I inject this "IConfigurationRoot" in each class of a project. And do I have to repeat this Startup class in each class Library? Why is this not part of .NET Core Framework?
推荐答案
根据面向对象编程中信息隐藏的原理,大多数类不需要访问您的应用程序配置。只有您的主应用程序类才需要直接访问此信息。您的类库应公开其属性和方法,以根据调用者认为必要的任何条件改变其行为,并且您的应用程序应使用其配置来设置正确的属性。
By the principle of Information Hiding in Object-Oriented Programming, most classes should not need to have access to your application configuration. Only your main application class should need to directly have access to this information. Your class libraries should expose properties and methods to alter their behavior based on whatever criteria their callers deem necessary, and your application should use its configuration to set the right properties.
例如,DateBox不需要知道时区信息如何存储在应用程序配置文件中-它只需要知道它具有DateBox.TimeZone属性,就可以在运行时检查它所在的时区。
For example, a DateBox shouldn't need to know how timezone information is stored in your application configuration file - all it needs to know is that it has a DateBox.TimeZone property that it can check at runtime to see what timezone it is in.
这篇关于从.NET Core / ASP.NET Core中的类库访问App关键数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!