下面是 Startup.cs 的模板代码。
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 的结构函数中,这自己就是可以的,如下代码所示:
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 容器中
public void ConfigureServices(IServiceCollection services) { services.AddTransient<MyClass>(); services.AddControllers(); }
生成 MyClass 实例
在 MyClass 的挪用方处通过 DI 生成实例,这里以 Controller 处为例,如下代码所示:
public class MyController : ControllerBase { private MyClass _myClass; public MyController(MyClass myClass) { _myClass = myClass; } }
这样是不是就完美的实现了在 MyClass 中利用 Configuration 了?
尚有一种更简朴粗暴的做法,无需注入, 只需界说一个静态的类,在 Startup 中将 IConfiguration 赋值给该静态类生存即可,参考代码如下: