【发布时间】:2015-05-25 17:17:29
【问题描述】:
我正在为 ASP.NET 5 (vNext) 中的一些概念而苦苦挣扎。
其中之一是用于配置的依赖注入方法。似乎我必须一直通过堆栈传递一个参数。我可能误解了什么或做错了。
假设我有一个名为“contactEmailAddress”的配置属性。下新订单时,我将使用该配置属性发送电子邮件。考虑到这种情况,我的 ASP.NET 5 堆栈将如下所示:
Startup.cs
public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment environment)
{
var configuration = new Configuration().AddJsonFile("config.json");
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseErrorPage();
app.UseMvc(routes =>
{
routes.MapRoute("default",
"{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index" });
}
);
app.UseWelcomePage();
}
AppSettings.cs
public class AppSettings
{
public string ContactEmailAddress { get; set; }
}
config.json
{
"AppSettings": {
"ContactEmailAddress":"support@mycompany.com"
}
}
OrderController.cs
[Route("orders")]
public class OrdersController : Controller
{
private IOptions<AppSettings> AppSettings { get; set; }
public OrdersController(IOptions<AppSettings> appSettings)
{
AppSettings = appSettings;
}
[HttpGet("new-order")]
public IActionResult OrderCreate()
{
var viewModel = new OrderViewModel();
return View(viewModel);
}
[HttpPost("new-order")]
public IActionResult OrderCreate(OrderViewModel viewModel)
{
return new HttpStatusCodeResult(200);
}
}
Order.cs
public class Order()
{
public void Save(IOptions<AppSettings> appSettings)
{
// Send email to address in appSettings
}
public static List<Order> FindAll(IOptions<AppSettings> appSettings)
{
// Send report email to address in appSettings
return new List<Order>();
}
}
如上例所示,我将AppSettings 传递给整个堆栈。这感觉不正确。更让我担心的是,如果我尝试使用需要访问配置设置的第三方库,这种方法将不起作用。第三方库如何访问配置设置?我是不是误会了什么?有没有更好的方法来做到这一点?
【问题讨论】:
-
这只是一个电子邮件地址还是多个地址?
标签: c# asp.net asp.net-mvc asp.net-core asp.net-core-mvc