从.NET Core / ASP.NET Core中的类库访问App关键数据

编程入门 行业动态 更新时间:2024-10-25 09:30:32
本文介绍了从.NET Core / ASP.NET Core中的类库访问App关键数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

要访问类库中的应用键,是否需要在每个需要访问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();

这就是我在 Microsoft文档,但这看起来非常多余。

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关键数据

本文发布于:2023-11-14 02:52:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586022.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类库   关键   数据   Core   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!