[英]What is the difference between using the service collection to configure settings or adding a singleton in .Net Core?
On startup of our asp net core applications we read a whole bunch of configuration from our appsettings.json
and map it to a concrete type that we inject in our service layer. 在启动ASP网络核心应用程序时,我们从appsettings.json
读取了一堆配置并将其映射到我们注入服务层的具体类型。
Consider the two examples below : 考虑以下两个示例:
A : services.AddSingleton(Configuration.GetSection("Auth0").Get<Auth0Settings>());
答: services.AddSingleton(Configuration.GetSection("Auth0").Get<Auth0Settings>());
B : services.Configure<Auth0Settings>(Configuration);
B: services.Configure<Auth0Settings>(Configuration);
I know using option AI can simply inject the concrete type into my constructor and use it whereas with option BI am required to use the Options Pattern 我知道使用选项AI可以简单地将具体类型注入到我的构造函数中并使用它,而使用选项BI则需要使用选项模式
Im unsure what benefits option B provides over option A and why I would use it. 不确定选项B相对于选项A有什么好处,为什么我会使用它。
In the end both approaches give the same result and you cann access an instance of Auth0Settings
via DI in eg your controllers. 最后,两种方法都给出相同的结果,您Auth0Settings
通过DI在例如控制器中访问Auth0Settings
实例。
For me there are two arguments in favor of the Options-Pattern . 对我来说,有两个论点支持Options-Pattern 。
Expressivness - you make a clear destinction about application logic (services) and configuration (options). 可表达性 -您明确确定了应用程序逻辑(服务)和配置(选项)。 This make your code better to read and your intent easer to understand. 这使您的代码更易于阅读,使您的意图更易于理解。
Flexibility - the Options-Pattern provides additional features (like validation and post-processing) 灵活性 -选项模式提供了其他功能(例如验证和后处理)
Although you might not need the additional features the first argument is still on the plate. 尽管您可能不需要其他功能,但第一个参数仍然存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.