首页 > 解决方案 > 如何在 Startup.cs 中实例化一个单例类,然后在 net core 中使用?

问题描述

我正在从我的 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-coresingleton

解决方案


由于您使用 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"
    }
}

然而,将应用程序配置信息传递给服务的推荐方法是使用选项模式


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"
    }
}

推荐阅读