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();
}
}
解决方案
在 .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;
}
}