我目前正在将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