ASP.Net Core 2中的全局变量

Luk*_*son 8 c# asp.net-core asp.net-core-2.0

我正在ASP.NET Core中开发Web应用程序,当前有大量密钥,例如条带帐户密钥。与其将它们分散在整个项目中的不同类中,不如将它们全部放置在json中,以便可以在全局范围内对其进行访问。我尝试将它们放在appsettings.json中,但无法在任何地方访问它们。

nur*_*guy 11

我经常用连接字符串和其他全局常量来做这种事情。首先为所需的变量创建一个类。在我的项目中,它就是MDUOptions您想要的。

public class MDUOptions
{
    public string mduConnectionString { get; set; }
    public string secondaryConnectionString { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

现在在您的Startup.cs ConfigureServices方法中:

Action<MDU.MDUOptions> mduOptions = (opt =>
{
    opt.mduConnectionString = Configuration["ConnectionStrings:mduConnection"];
});
services.Configure(mduOptions);
services.AddSingleton(resolver => resolver.GetRequiredService<IOptions<MDUOptions>>().Value);
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用DI通过代码访问它:

public class PropertySalesRepository : IPropertySalesRepository
{
    private static string _mduDb;

    public PropertySalesRepository(MDUOptions options)
    {
        _mduDb = options.mduConnectionString;
    }
    ....
}
Run Code Online (Sandbox Code Playgroud)

在我的情况下,我想要的唯一属性是字符串,但是我可以使用整个options类。


pri*_*sar 6

在appsettings.json中保留变量。

{
    "foo": "value1",
    "bar": "value2",
}
Run Code Online (Sandbox Code Playgroud)

创建AppSettings类。

public class AppSettings
{
    public string foo { get; set; }

    public string bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Startup.cs文件中注册。

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettings>(Configuration);
}
Run Code Online (Sandbox Code Playgroud)

用法,

public class MyController : Controller
{
    private readonly IOptions<AppSettings> _appSettings;

    public MyController(IOptions<AppSettings> appSettings)
    {
        _appSettings = appSettings;
    }
    var fooValue = _appSettings.Value.foo;
    var barValue = _appSettings.Value.bar;
}
Run Code Online (Sandbox Code Playgroud)