我目前正在將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);
}
我還沒有編譯一切還沒有,因爲我還有更多的在遷移代碼的其餘部分中去,所以我甚至不知道底部的兩個甚至是有效的。
我還沒有找到關於這些不同的實現的任何明確的文檔,特別是底部的兩個,有人可以幫助解釋差異?
嗨工廠是在你不想創建多次實例並且這個對象依賴於許多其他服務的情況下使用。但在你的情況下,它是單一的類,你不會模擬配置進行測試,所以它作爲工廠使用它是沒有意義的。你應該去DI。 –
請在這裏閱讀更多: - http://dotnetliberty.com/index.php/2016/05/09/asp-net-core-factory-pattern-dependency-injection/ –
@YashveerSingh,感謝您的鏈接。不過,我仍然不清楚使用'Func'lambda與傳遞實例的區別。 – Svek