简体   繁体   中英

How can “IConfiguration object is registered with DI by default” in Startup.cs in .NET Core 2

In, aspnet core 2, when we want to to Access configuration during startup, we can do it thanks to dependency injection as far as I understood.

For this code in below, how can we pass IConfiguration object to this class with benefits of Dependency Injection ;

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

I saw a sentence:

" The IConfiguration object is registered with DI by default."

How can we succeed this?

In program.cs there is a code like this, do we set IConfiguration object in startup.cs class with this code below? I thought .UseStartup() code carries out this job(passing IConfiguration object to Startup class) for us. But how?

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(SetupConfiguration)
          .UseStartup<Startup>();

    private static void SetupConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder builder)
    {
        //Remove the default configuration options
        builder.Sources.Clear();

        builder.AddJsonFile("config.json", false, true).
            AddEnvironmentVariables();
    }
}

I would be so happy if someone can explain this with deep details.

The dependency injection is handled internally for you for the IConfiguration instance. The technical details are easy to find if you browse around the source code . In this case, there is a helper class that mimics a basic DI container, you can see this here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM