从 .NET Core/ASP.NET Core 中的类库访问应用程序密钥数据 [英] Access App key data from class libraries in .NET Core / ASP.NET Core

查看:32
本文介绍了从 .NET Core/ASP.NET Core 中的类库访问应用程序密钥数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

访问类库中的App Key,是否需要在每个需要访问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 中的类库访问应用程序密钥数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆