我可能已经长时间盯着这个了,但是我最近几天已经跳进了MVC6 for asp.net,而我真的很享受这个,我似乎无法找到一个方便的方法来访问它之后的配置在Start.cs中定义
Configuration = new Configuration()
.AddJsonFile("config.json")
...
那么,我需要将它添加到DI中还是已经存在?或者我应该在需要使用它时创建一个新实例,因为可以创建不同的配置(例如IIdentityMessageService)创建sendgrid.json并在Service本身中加载它?
可能有一个非常简单的解决方案,但就像我说我已经看了好几天了。
只在Startup.cs中加载配置。如果您以后在其他地方需要它们,您可以将值加载到适当的POCO中并在DI中注册它们,以便您可以将它们注入您需要的地方。这允许您以对应用程序有意义的方式在不同文件和不同POCO中组织配置。在依赖注入中已经内置了对此的支持。您将如何做到这一点:
用于配置的POCO:
public class SomeOptions
{
public string EndpointUrl { get; set; }
}
您的Startup.cs将配置加载到POCO中并将其注册到DI中。
public class Startup
{
public Startup()
{
Configuration = new Configuration()
.AddJsonFile("Config.json")
.AddEnvironmentVariables();
}
public IConfiguration Configuration { get; set; }
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<SomeOptions>(options =>
options.EndpointUrl = Configuration.Get("EndpointUrl"));
services.AddMvc();
}
}
然后在您的控制器中通过依赖注入获取您在Startup.cs中创建的配置POCO,如下所示:
public class SomeController
{
private string _endpointUrl;
public SomeController(IOptions<SomeOptions> options)
{
_endpointUrl = options.Options.EndpointUrl;
}
}
测试了1.05-beta1版本的aspnet5。
有关更多信息,请参阅 ASP.Net 5配置的基础知识。
只在Startup.cs中加载配置。如果您以后在其他地方需要它们,您可以将值加载到适当的POCO中并在DI中注册它们,以便您可以将它们注入您需要的地方。这允许您以对应用程序有意义的方式在不同文件和不同POCO中组织配置。在依赖注入中已经内置了对此的支持。您将如何做到这一点:
用于配置的POCO:
public class SomeOptions
{
public string EndpointUrl { get; set; }
}
您的Startup.cs将配置加载到POCO中并将其注册到DI中。
public class Startup
{
public Startup()
{
Configuration = new Configuration()
.AddJsonFile("Config.json")
.AddEnvironmentVariables();
}
public IConfiguration Configuration { get; set; }
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<SomeOptions>(options =>
options.EndpointUrl = Configuration.Get("EndpointUrl"));
services.AddMvc();
}
}
然后在您的控制器中通过依赖注入获取您在Startup.cs中创建的配置POCO,如下所示:
public class SomeController
{
private string _endpointUrl;
public SomeController(IOptions<SomeOptions> options)
{
_endpointUrl = options.Options.EndpointUrl;
}
}
测试了1.05-beta1版本的aspnet5。
有关更多信息,请参阅 ASP.Net 5配置的基础知识。