在 ASP.NET CORE 中的 Startup.cs 中设置动态变量

GRU*_*119 2 c# asp.net asp.net-core

我无法理解在 Startup.cs 中设置动态变量的最佳方法。我希望能够在控制器或视图中获取该值。我希望能够将值存储在内存中,而不是 JSON 文件中。我已经研究过将值设置为会话变量,但这似乎不是一个好的实践或工作。在 Startup.cs 中设置动态变量的最佳实践是什么?

public class Startup
    {
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        //services.AddDbContext<>(options => options.UseSqlServer(Configuration.GetConnectionString("Collections_StatsEntities")));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*att 6

全局变量和静态变量都很糟糕。ASP.NET Core 包含专门内置的 DI 来避免这些问题,因此不要重新引入它们。正确的做法是使用配置。开箱即用的 ASP.NET Core 应用程序支持通过 JSON(appsettings.jsonappsettings.{environment}.json)、命令行、用户机密(也是 JSON,但存储在您的配置文件中,而不是项目内)和环境变量进行配置。如果您需要其他配置源,则可以使用其他现有的提供程序,或者您甚至可以自行推出以使用您喜欢的任何提供程序。

无论您使用哪个配置源,最终结果都将是所有源的所有配置设置进入IConfigurationRoot. 虽然从技术上讲您可以直接使用它,但最好使用IOptions<T>和 类似提供的强类型配置。简而言之,您创建一个代表配置中某些部分的类:

public class FooConfig
{
    public string Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

{ Foo: { Bar: "Baz" } }例如,这对应于 JSON 中的内容。然后,ConfigureServicesStartup.cs

services.Configure<FooConfig>(Configuration.GetSection("Foo"));
Run Code Online (Sandbox Code Playgroud)

最后,在您的控制器中,例如:

 public class FooController : Controller
 {
     private IOptions<FooConfig> _config;

     public FooController(IOptions<FooConfig> config)
     {
         _config = config ?? throw new ArgumentNullException(nameof(config));
     }

     ...
 }
Run Code Online (Sandbox Code Playgroud)

配置是在启动时读取的,并且从技术上讲,配置随后存在于内存中,因此您对必须使用 JSON 之类的东西的抱怨在大多数情况下是没有意义的。但是,如果您确实想要完全内存化,可以使用内存配置提供程序。但是,如果可以的话,将您的配置外部化总是更好。