【问题标题】:how to instantiate a singleton class in Startup.cs and then use in net core?如何在 Startup.cs 中实例化一个单例类,然后在 net core 中使用?
【发布时间】:2021-03-03 17:45:29
【问题描述】:

我正在从我的 appsetting.json 中创建的对象创建一个对象,我通过单例添加它,但我不知道如何访问这些值。

我的班级:

public class UserConfiguration
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string SecretKey{ get; set; }
}

在我的 startup.cs 中

 var userCfg = Configuration.GetSection("UserConfig").Get<UserConfiguration>(); //.> success i've values
 services.AddSingleton(userCfg);

 services.AddControllers();

我想使用这个类,我从我的控制器 api 调用这个类。

public class UserService : BaseService
{
    public UserService(IConfiguration config): base(configuration)
    {

    }

    public string GetData()
    {
        var userConfg = new UserConfiguration();
        var key = user.SecretKey;  //--> null but a instance is empty

        return "ok"
    }
}

但我不知道如何拯救我在Startup.cs中加载的单例的值

【问题讨论】:

标签: c# .net-core singleton


【解决方案1】:

由于您使用 DI 容器将 UserConfiguration 注册为 Singleton,因此您可以注入此对象 UserService 构造函数:

public class UserService : BaseService
{
    private UserConfiguration _userConfiguration;
    public UserService(IConfiguration config, UserConfiguration userConfiguration): base(configuration)
    {
        _userConfiguration = userConfiguration; //Injected in constructor by DI container
    }

    public string GetData()
    {
        var key = _userConfiguration .SecretKey;

        return "ok"
    }
}

不过,将应用程序配置信息传递给服务的推荐方法是使用 Options pattern


services.Configure<UserConfiguration>(Configuration.GetSection("UserConfig"));

services.AddControllers();

添加然后访问配置选项:

public class UserService : BaseService
{
    private UserConfiguration _userConfiguration;
    public UserService(IConfiguration config, IOptions<UserConfiguration> userConfiguration): base(configuration)
    {
        _userConfiguration = userConfiguration.Value; //Injected in constructor by DI container
    }

    public string GetData()
    {
        var key = _userConfiguration .SecretKey;

        return "ok"
    }
}

【讨论】:

    猜你喜欢
    • 2019-11-04
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多