gpt4 book ai didi

c# - 在 ASP.NET 5 (vNext) 中获取配置值

转载 作者:可可西里 更新时间:2023-11-01 09:04:05 25 4
gpt4 key购买 nike

我对 ASP.NET 5 (vNext) 中的一些概念感到困惑。

其中之一是用于配置的依赖注入(inject)方法。好像我必须通过堆栈一直传递一个参数。我可能误解了什么或做错了。

假设我有一个名为“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 传递给整个堆栈。这感觉不对。更让我担心的是,如果我尝试使用需要访问配置设置的第三方库,这种方法将不起作用。第三方库如何访问配置设置?我误会了什么吗?有更好的方法吗?

最佳答案

您正在纠缠 2 个不同的运行时资源提供程序,AppSettingsDependency Injection

AppSettings,提供对应用程序特定值(如 UICulture 字符串、联系电子邮件等)的运行时访问。

DI 容器 是管理服务访问及其生命周期范围的工厂。例如,如果 MVC Controller 需要访问您的 EmailService,您可以配置

   public void ConfigureServices(IServiceCollection services)
{
// Add all dependencies needed by Mvc.
services.AddMvc();

// Add EmailService to the collection. When an instance is needed,
// the framework injects this instance to the objects that needs it
services.AddSingleton<IEmailService, EmailService>();
}

然后,如果我们的 Home Controller 需要访问您的 EmailService,我们通过将其作为参数添加到 Controller 构造函数来添加对其接口(interface)的依赖

public class HomeController : Controller
{
private readonly IEmailService _emailService;
private readonly string _emailContact;

/// The framework will inject an instance of an IEmailService implementation.
public HomeController(IEmailService emailService)
{
_emailService = emailService;
_emailContact = System.Configuration.ConfigurationManager.
AppSettings.Get("ContactEmail");
}

[HttpPost]
public void EmailSupport([FromBody] string message)
{
if (!ModelState.IsValid)
{
Context.Response.StatusCode = 400;
}
else
{
_emailService.Send(_emailContact, message);

依赖注入(inject)的目的是管理服务的访问和生命周期

在前面的示例中,在我们的应用程序 Startup 中,我们将 DI 工厂配置为将 IEmailService 的应用程序请求与 EmailService 相关联。因此,当我们的 Controller 由 MVC 框架 实例化时,框架注意到我们的 Home Controller 需要 IEmailService,框架检查我们的应用程序服务集合。它找到映射指令并将 Singleton EmailService(占用接口(interface)的后代)注入(inject)到我们的家庭 Controller 中。

super 多态因子 - 可恶!

为什么这很重要?

如果您的联系电子邮件发生变化,您可以更改 AppSetting 值并完成。 ConfigurationManager 对“ContactEmail”的所有请求都已全局更改。字符串很容易。当我们可以散列时不需要注入(inject)。

如果您的存储库、电子邮件服务、日志服务等发生变化,您需要一种全局方式来更改对该服务的所有引用。服务引用不像不可变字符串文字那样容易传输。服务实例化应由工厂处理以配置服务的设置和依赖项。

因此,在一年内您开发了一个 RobustMailService:

Class RobustMailService : IEmailService
{

....

}

只要您的新 RobustMailService 继承并实现了 IEmailService 接口(interface),您就可以通过更改全局替换对邮件服务的所有引用:

   public void ConfigureServices(IServiceCollection services)
{
// Add all dependencies needed by Mvc.
services.AddMvc();

// Add RobustMailService to the collection. When an instance is needed,
// the framework injects this instance to the objects that needs it
services.AddSingleton<IEmailService, RobustMailService>();
}

关于c# - 在 ASP.NET 5 (vNext) 中获取配置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30443133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com