我是靠谱客的博主 魁梧大门,这篇文章主要介绍如何在ASP.NET Core 的任意类中注入Configuration,现在分享给大家,希望可以做个参考。

遇到的问题

我已经通读了 MSDN 上关于 Configuration 的相关内容,文档说可实现在 application 的任意位置访问 Configuration .

下面是 Startup.cs 的模板代码。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class Startup {     public Startup(IHostingEnvironment env)     {         var builder = new ConfigurationBuilder()             .SetBasePath(env.ContentRootPath)             .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)             .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);         if (env.IsEnvironment("Development"))         {             // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.             builder.AddApplicationInsightsSettings(developerMode: true);         }         builder.AddEnvironmentVariables();         Configuration = builder.Build();     }     public IConfigurationRoot Configuration { get; }     // This method gets called by the runtime. Use this method to add services to the container     public void ConfigureServices(IServiceCollection services)     {         // Add framework services.         services.AddApplicationInsightsTelemetry(Configuration);         services.AddMvc();     }     // This method gets called by the runtime. Use this method to configure the HTTP request pipeline     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)     {         loggerFactory.AddConsole(Configuration.GetSection("Logging"));         loggerFactory.AddDebug();         app.UseApplicationInsightsRequestTelemetry();         app.UseApplicationInsightsExceptionTelemetry();         app.UseMvc();     } }

我知道可以通过 DI 的方式将 Configuration 注入到 Controller,Service,Repository 等地方,但在真实项目中,会有很多类是在这三块之外的。

请问我如何在这三大块之外实现 Configuration 的注入呢?换句话说:可以在任意类中实现 Configuration 的注入... 😭

解决方案

在 .NET Core 中你可以将 IConfiguration 作为参数直接注入到 Class 的构造函数中,这本身就是可以的,如下代码所示:

复制代码
1
2
3
4
5
6
7
8
public class MyClass  {     private IConfiguration configuration;     public MyClass(IConfiguration configuration)     {         ConnectionString = new configuration.GetValue<string>("ConnectionString");     } }

接下来要做的就是 new MyClass(),很显然这样做是不行的,因为你的构造函数还需要一个 IConfiguration 类型的参数,所以你需要将 new MyClass() 塞入到 Asp.NET Core 的 DI 链中。

思路也很简单。

  • 将 MyClass 注入到 ServiceCollection 容器中
复制代码
1
2
3
4
5
        public void ConfigureServices(IServiceCollection services)         {             services.AddTransient<MyClass>();             services.AddControllers();         }
  • 生成 MyClass 实例

在 MyClass 的调用方处通过 DI 生成实例,这里以 Controller 处为例,如下代码所示:

复制代码
1
2
3
4
5
6
7
8
9
public class MyController : ControllerBase {     private MyClass _myClass;     public MyController(MyClass myClass)     {         _myClass = myClass;     } }

这样是不是就完美的实现了在 MyClass 中使用 Configuration 了?

还有一种更简单粗暴的做法,无需注入, 只需定义一个静态的类,在 Startup 中将 IConfiguration 赋值给该静态类保存即可,参考代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
public static class MyAppData {     public static IConfiguration Configuration; } public Startup(IConfiguration configuration) {     Configuration = configuration;     MyAppData.Configuration = configuration; }

然后就可以在项目的各处访问 MyAppData.Configuration 啦。

总结

在 Asp.Net 时代,读取配置文件真的是一点都不需要操心,一个 ConfigurationManager 走天下😄😄😄,比如下面的代码:

复制代码
1
    private static string AppKey = ConfigurationManager.AppSettings["AppKey"];

反倒在 Asp.Net Core 中却有点懵逼了,就像题主说的,我想在任意类中都可以读取 Configuration 😂😂😂,问题的差异来自于 Asp.Net Core 使用了 DI先行 的打法,哈哈,忘了过去吧,从 ♥ 开始 ...

以上就是如何在 ASP.NET Core 的任意类中注入Configuration 的详细内容,更多关于ASP.NET Core 注入Configuration 的资料请关注靠谱客其它相关文章!

最后

以上就是魁梧大门最近收集整理的关于如何在ASP.NET Core 的任意类中注入Configuration的全部内容,更多相关如何在ASP.NET内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(114)

评论列表共有 0 条评论

立即
投稿
返回
顶部