相关疑难解决方法(0)

IOptions注入

在我看来,让域服务需要一个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给我带来了什么而不是旧式的注入方式?

c# asp.net-core

23
推荐指数
3
解决办法
1万
查看次数

无需依赖注入即可访问配置

我想知道是否有一种方法可以在不使用依赖注入的情况下访问Configuration(Microsoft.Extensions.Configuration).我看到的只有一些例子是通过构造函数注入(使用IOptions或直接注入Configuration).

我的困境是我有一个实用类 - 而不是一个服务 - 它有静态方法来动态地做事.在一些静态方法中,我想动态地从appsettings.json中检索几个属性.由于这是一个严格的实用程序类,我不希望必须将此类注入需要使用该实用程序中的一个或两个方法的其他每个类.

关于如何在没有某种依赖注入的情况下访问appsettings.json的属性的任何想法.

仅供参考:使用c#和.net核心1.1

c# .net-core

21
推荐指数
3
解决办法
6009
查看次数

标签 统计

c# ×2

.net-core ×1

asp.net-core ×1