2017-04-04 71 views
1

我具有类似于这个代码在Startup.cs在ConfigureServices()中仍然可以访问强类型设置吗?

services.Configure<AppSettings>(
    Configuration.GetSection("AppSettings")); 

services.AddScoped<IMyService, MyService>(); 
services.AddScoped((_) => MyFactory.Create(
    Configuration["AppSettings:Setting1"], 
    Configuration["AppSettings:Setting2"], 
    Configuration["AppSettings:Setting3"])); 

我想的AppSettings的实例传递到MyFactory.Create()。这样的实例是否可用?有没有办法得到它的一个实例?

我想消除我当前代码中的冗余,并利用我的AppSettings类的一些好处(例如,它有一些默认设置和一些方便的只读属性,这些属性是其他属性的函数)。

它可能是这个样子:

services.Configure<AppSettings>(
    Configuration.GetSection("AppSettings")); 

var appSettings = ???; 
services.AddScoped<IMyService, MyService>(); 
services.AddScoped((_) => MyFactory.Create(appSettings)); 

在什么地方的 “???” 去?

回答

2

您可以使用Microsoft.Extensions.Configuration.Binder包。这在IConfigurationSection接口上提供了Bind扩展方法,并允许您传入选项类的实例。它会尝试以递归方式将配置值绑定到您的类属性。

引用的文档:

尝试通过匹配针对配置键递归属性名称为给定的对象实例的配置值结合。

在你的情况下,代码将如下所示:

// Create a new, empty instance of AppSettings 
var appSettings = new AppSettings(); 

// Bind values from the 'AppSettings' section to the instance 
Configuration.GetSection("AppSettings").Bind(appSettings); 

请记住,如果你仍然想在通过依赖注入您的应用程序注入IOptions<AppSettings>,你还是要配置选项通过

services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); 
+0

这看起来像我想要的!我将在接下来的几天内实施,并在确认时将其标记为答案。谢谢。 – Chris

+0

@Chris是否为您解决问题? –

+1

当然可以!标记为答案。抱歉耽搁了。 – Chris

相关问题