2017-01-18 127 views
2

我目前正在將ASP.NET Web Api項目遷移到ASP.NET Core,並且我已經對如何正確完成存儲配置屬性的值並使配置可以訪問我的整個項目感到有點遺憾。ASP.NET核心依賴注入:工廠和實例之間的區別?

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

我還沒有編譯一切還沒有,因爲我還有更多的在遷移代碼的其餘部分中去,所以我甚至不知道底部的兩個甚至是有效的。

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

+0

嗨工廠是在你不想創建多次實例並且這個對象依賴於許多其他服務的情況下使用。但在你的情況下,它是單一的類,你不會模擬配置進行測試,所以它作爲工廠使用它是沒有意義的。你應該去DI。 –

+0

請在這裏閱讀更多: - http://dotnetliberty.com/index.php/2016/05/09/asp-net-core-factory-pattern-dependency-injection/ –

+0

@YashveerSingh,感謝您的鏈接。不過,我仍然不清楚使用'Func'lambda與傳遞實例的區別。 – Svek

回答

4

不同之處在於,當您使用「工廠」時,每次請求實例時都會調用它。它基本上是對你想要的東西進行構建的「描述」,如果你需要在運行時需要某些東西來強化實例,這可以派上用場。

在你的情況下,你沒有對配置做任何事情,所以它最好只是作爲一個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; 
}); 

應當注意的是,因爲使用的是單身,有將兩者之間的差異很小,因爲它一定會無論如何都要調用一次,但瞬態/作用域依賴可能會有很大的差異。

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

+0

這個答案很有意義。我很欣賞清晰度。 – Svek