从启动类访问配置对象 [英] Access to Configuration object from Startup class
问题描述
我想从我的公司在ASP.NET vNext项目的许多控制器中访问Active Directory,并将域名插入到config.json文件中,以便可以从Configuration类访问它.我发现每次访问我的config.json时总是实例化一个新的Configuration对象很麻烦,是否有任何方法可以通过IConfiguration
API访问初始化为Startup类的Configuration类?
I would like to access to the Active Directory from my company in many controllers from my ASP.NET vNext project, and I inserted the domain name into my config.json file, so I can access it from the Configuration class. I find it heavy to always instantiate a new Configuration object at every time I want to access to my config.json, is there any way through the IConfiguration
API to access to the Configuration class initialized into the Startup class ?
推荐答案
如何执行此操作的示例:
An example of how you can do this:
假设您有一个config.json,如下所示:
Let's assume you have a config.json like below:
{
"SomeSetting1": "some value here",
"SomeSetting2": "some value here",
"SomeSetting3": "some value here",
"ActiveDirectory": {
"DomainName": "DOMAIN-NAME-HERE"
}
}
创建具有您的选项信息的POCO类型:
Create a POCO type having your option information:
public class ActiveDirectoryOptions
{
public string DomainName { get; set; }
}
在Startup.cs中,配置服务时:
In Startup.cs, when configuring services:
services.Configure<ActiveDirectoryOptions>(optionsSetup =>
{
//get from config.json file
optionsSetup.DomainName = configuration.Get("ActiveDirectory:DomainName");
});
在所有想要获得此配置设置的控制器中,执行类似...的操作,此处这些选项由DI系统注入:
In all controllers which want to get this config setting, do something like...Here the options is injected by the DI system:
public class HomeController : Controller
{
private readonly IOptions<ActiveDirectoryOptions> _activeDirectoryOptions;
public HomeController(IOptions<ActiveDirectoryOptions> activeDirectoryOptions)
{
_activeDirectoryOptions = activeDirectoryOptions;
}
public IActionResult Index()
{
string domainName = _activeDirectoryOptions.Options.DomainName;
........
}
}
回复评论:
我可以想到几种选择:
Responding to the comment:
There are couple of options that I can think of:
-
您可以在操作中执行
From within the action, you can do
var options = HttpContext.RequestServices.GetRequiredService<IOptions<ActiveDirectoryOptions>>().Options;
您可以为用FromServicesAttribute
装饰的动作设置一个参数.该属性将导致从DI中检索参数值.
示例:
You can have a parameter to the action which is decorated with FromServicesAttribute
. This attribute will cause the parameter value to be retrieved from the DI.
Example:
public IActionResult Index([FromServices] IOptions<ActiveDirectoryOptions> options)
相对于#1,我更喜欢#2,因为在进行单元测试时,它会为您提供所有相关部件的信息.
I prefer #2 over #1 as in case of unit testing it gives you information on all dependent pieces.
这篇关于从启动类访问配置对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!