2017-01-18 128 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