ASP.Net Core 2中的全局变量 [英] Global Variables in ASP.Net Core 2
问题描述
我正在ASP.NET Core中开发一个Web应用程序,目前有大量密钥,例如条带帐户密钥.与其将它们分散在整个项目中的不同类中,我不希望将它们全部放置在json中,以便可以在全局范围内对其进行访问.我尝试将它们放置在appsettings.json中,但无法在任何地方访问它们.
I am developing a web application in ASP.NET Core and currently have a large set of keys, such as stripe account keys. Instead of having them spread throughout the project in different classes I would like to place them all together in json where they could be accessed globally. I have tried placing them in appsettings.json but cannot access them anywhere.
推荐答案
我经常用连接字符串和其他全局常量来做这种事情.首先为所需的变量创建一个类.在我的项目中,它是MDUOptions
,但是您想要的任何内容.
I often do this kind of thing with connection strings and other global constants. First create a class for those variables that you need. In my project it is MDUOptions
but whatever you want.
public class MDUOptions
{
public string mduConnectionString { get; set; }
public string secondaryConnectionString { get; set; }
}
现在在您的Startup.cs ConfigureServices方法中:
Now in your Startup.cs ConfigureServices method:
Action<MDU.MDUOptions> mduOptions = (opt =>
{
opt.mduConnectionString = Configuration["ConnectionStrings:mduConnection"];
});
services.Configure(mduOptions);
services.AddSingleton(resolver => resolver.GetRequiredService<IOptions<MDUOptions>>().Value);
现在,您可以使用DI通过代码访问它:
Now you use DI to access it in code:
public class PropertySalesRepository : IPropertySalesRepository
{
private static string _mduDb;
public PropertySalesRepository(MDUOptions options)
{
_mduDb = options.mduConnectionString;
}
....
}
在我的情况下,我想要的唯一属性是字符串,但是我可以使用整个选项类.
In my case the only property I wanted was the string but I could have used the entire options class.
这篇关于ASP.Net Core 2中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!