在我看来,让域服务需要一个IOptions实例来传递它配置是一个坏主意.现在我已经将额外的(不必要的?)依赖项拉入库中.我已经看到很多在网络上注入IOse的例子,但是我没有看到它带来的额外好处.
为什么不将实际的POCO注入服务?
services.AddTransient<IConnectionResolver>(x =>
{
var appSettings = x.GetService<IOptions<AppSettings>>();
return new ConnectionResolver(appSettings.Value);
});
Run Code Online (Sandbox Code Playgroud)
甚至使用这种机制:
AppSettings appSettings = new AppSettings();
Configuration.GetSection("AppSettings").Bind(appSettings);
services.AddTransient<IConnectionResolver>(x =>
{
return new ConnectionResolver(appSettings.SomeValue);
});
Run Code Online (Sandbox Code Playgroud)
使用设置:
public class MyConnectionResolver
{
// Why this?
public MyConnectionResolver(IOptions<AppSettings> appSettings)
{
...
}
// Why not this?
public MyConnectionResolver(AppSettings appSettings)
{
...
}
// Or this
public MyConnectionResolver(IAppSettings appSettings)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
为什么附加依赖?IOptions给我带来了什么而不是旧式的注入方式?
选项模式使我能够创建包含配置值的选项对象,如下所述:https : //docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.1
我需要IDesignTimeDbContextFactory实现中一个选项对象的值,以供EF在创建模型时使用。(该配置部分中的值将用于数据播种,因此我向数据库上下文构造函数中添加了IOptions。)
由于我无权访问IServiceCollection(因为它是设计时间,就像运行“ dotnet ef迁移添加”时一样),所以我需要有另一种方法可以将IConfigurationSection(代表我感兴趣的部分)转换为自定义Options类。
我可以知道如何在没有依赖注入的情况下做到这一点吗?