.net 带连接字符串的IOptions

ig9co6j1  于 2022-12-24  发布在  .NET
关注(0)|答案(2)|浏览(107)

我有非常简单的应用程序设置:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=test;Database=test;Trusted_Connection=True;"
  },
  "AllowedHosts": "*"
}

连接字符串的类:

public class ConnectionStrings
    {
      public string DefaultConnection { get; set; }
    }

我在DI中这样注册:

builder.Services.AddOptions<ConnectionStrings>(builder.Configuration.GetConnectionString("DefaultConnection"));

我在构造函数中注入IOption,但它始终为null:

public class ShoppingCartRepository : IShoppingCartRepository
  {
    private readonly IOptions<ConnectionStrings> _connectionStrings;

    public ShoppingCartRepository(IOptions<ConnectionStrings> connectionStrings)
    {
      _connectionStrings = connectionStrings;
    }

    // ...
 
    }
  }

我可以对连接字符串使用IOptions吗?还是应该使用另一种方法?
使用连接字符串的最佳方式是什么?

ccrfmcuu

ccrfmcuu1#

AddOptions方法接受一个类型为string的参数,该参数是选项示例的名称,但是您将appsettings.json中的DefaultConnection值传递给它。
应在AddOptions之后添加Bind方法

builder.Services
    .AddOptions<ConnectionStrings>()
    .Bind(Configuration.GetSection("ConnectionStrings:DefaultConnection"));
fumotvh3

fumotvh32#

让我们从这里开始:

builder.Services.Configure<ConnectionStrings>(
    builder.Configuration.GetSection("ConnectionStrings")
)

相关问题