簡體   English   中英

ASP.NET核心依賴項注入:工廠和實例之間的區別?

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

我目前正在將一個ASP.NET Web Api項目遷移到ASP.NET Core,並且在如何正確完成存儲Configuration屬性的值並使整個項目都可以訪問該配置方面,我有些迷失了。

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);
}

我還沒有編譯所有內容,因為在遷移其余代碼方面還需要做更多工作,因此我什至不確定底部的兩個代碼是否有效。

我還沒有找到關於這些不同實現的任何清晰文檔,特別是底部的兩個,有人可以幫助解釋這些差異嗎?

區別在於,當您使用“工廠”時,每次請求實例時都會調用該工廠。 從本質上講,它是您如何構建事物的“描述”,如果您在運行時需要一些東西來實例化實例,這可能會派上用場。

在您的情況下,您對配置不執行任何操作,因此最好將其綁定為Singleton。 但是請考慮以下幾點:

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;
});

應該注意的是,因為您使用的是Singletons,所以兩者之間幾乎沒有什么區別,因為無論如何它只會被調用一次,但是對於Transient / Scoped依賴項可能會有很大的區別。

另一方面,如果您對配置部分感到困惑。 在這里快速閱讀: http : //dotnetcoretutorials.com/2016/12/26/custom-configuration-sections-asp-net-core/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM