简体   繁体   中英

ASP.NET Core Dependency Injection: The Difference Between Factory and Instance?

I am currently migrating an ASP.NET Web Api project to ASP.NET Core and I've gotten a bit lost on how to properly accomplish storing the value of the Configuration property and making the configuration accessible to my entire project.

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    // invoking a factory to create the service?
    services.AddSingleton(_ => Configuration);
    services.AddSingleton<IConfiguration>(_ => Configuration);

    // passing the instance of the service?
    services.AddSingleton(Configuration);
    services.AddSingleton<IConfigurationRoot>(Configuration);
}

I still haven't compiled everything yet as I still have a bit more to go in migrating the rest of the code, so I'm not even sure if the bottom two are even valid.

I didn't find any clear documentation about these different implementations yet, in particular the bottom two, can someone help explain the differences?

The difference is that when you use a "factory", it gets invoked each time an instance is requested. It's essentially a "description" for how you want things built, this can come in handy if you need something at runtime to compelete the instance.

In your case you are doing nothing with the configuration so it's better to just bind as a Singleton. But consider the following :

services.AddTransient(_ =>
{
    //Now I can do work in here at runtime to work out WHICH instance I should return
    //For example at runtime I could decide should I return configuration from appSettings.json or somewhere else?
    //Then I can return the one that I actually want to use. 
    return Configuration;
});

It should be noted that because you are using Singletons, there is going to be very little difference between the two since it's only going to be invoked once anyway, but with Transient/Scoped dependencies there can be big differences.

On another note, if you are confused about configuration sections. Take a quick read here : http://dotnetcoretutorials.com/2016/12/26/custom-configuration-sections-asp-net-core/

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