解决Startup.cs中的依赖关系

时间:2017-06-27 17:42:39

标签: c# configuration asp.net-core

我有一个新的Asp.Net核心应用程序,在appsettings.json文件中有以下条目:

{
  "DatabaseConnections": {
    "DatabaseUri": "https://localhost:8081",
    "ApplicationKey": "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
    "DatabaseName": "MyDatabase"
  }
}

我尝试使用ConfigureServices方法在.Bind方法中提取数据:

public class DatabaseConnections
{
    public string DatabaseUri { get; set; }

    public string ApplicationKey { get; set; }

    public string DatabaseName { get; set; }
}

private DatabaseConnections databaseSettings;

private DatabaseConnections DatabaseSettings
{
    get
    {
        if (databaseSettings == null)
        {
            databaseSettings = new DatabaseConnections();
            Configuration.Bind(databaseSettings);
        }

        return databaseSettings;
    }
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IDocumentClient>(
        new DocumentClient(
            new Uri(DatabaseSettings.DatabaseUri),
            DatabaseSettings.ApplicationKey));
}

但是,当我执行绑定时,设置都设置为null。但是如果我尝试在没有模型绑定的情况下这样做,它似乎工作正常:

public void ConfigureServices(IServiceCollection services)
{
    var databaseSettings = Configuration.GetSection("DatabaseConnections");

    services.AddSingleton<IDocumentClient>(
        new DocumentClient(
            new Uri(databaseSettings.GetValue<string>("DatabaseUri")),
            databaseSettings.GetValue<string>("ApplicationKey")));
}

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您可以构建服务提供者或使用字符串。

Configuration.GetSection("DatabaseConnections:DatabaseUri").Value

例如,

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();
    services.Configure<DatabaseConnections>(
        Configuration.GetSection("DatabaseConnections"));


    var sp = services.BuildServiceProvider();
    var databaseConnections = sp.GetService<IOptions<DatabaseConnections>>();

    services.AddSingleton<IDocumentClient>(
        new DocumentClient(new Uri(databaseConnections.Value.DatabaseUri)),
        databaseConnections.Value.ApplicationKey));
}

控制器

public class HomeController : Controller
{
    private readonly DatabaseConnections _databaseConnections;

    public HomeController(IOptions<DatabaseConnections> databaseConnections)
    {
        _databaseConnections = databaseConnections.Value;
    }
}

答案 1 :(得分:0)

另一个答案是好的,如果你想使用IOptions,无论出于什么原因我真的不喜欢这样做,而更喜欢绑定到一个类。

您可以在Configure Services方法中使用一行执行此操作:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(Configuration.GetSection("DatabaseConnections").Get<DatabaseConnections>());
}

看起来你错过了&#34; Get&#34;在最后,它接受配置部分并将其绑定到您的类。

更多信息:http://dotnetcoretutorials.com/2016/12/26/custom-configuration-sections-asp-net-core/