简体   繁体   English

如何在 Startup.cs 中实例化 singleton class 然后在网络核心中使用?

[英]how to instantiate a singleton class in Startup.cs and then use in net core?

I am creating an object from an object created in my appsetting.json, I add it through singleton but then I don't know how to access those values. I am creating an object from an object created in my appsetting.json, I add it through singleton but then I don't know how to access those values.

My class:我的 class:

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

In my startup.cs在我的startup.cs

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

 services.AddControllers();

and i want use this class and I call this class from my controller api.我想使用这个 class 我从我的 controller Z8A5DA52ED126447D359E70C0572 中调用这个 class。

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

but I don't know how to rescue the values of the singleton that I loaded in the Startup.cs但我不知道如何挽救我在 Startup.cs 中加载的 singleton 的值

Since you're registering UserConfiguration as Singleton with DI container, you can inject this object UserService constructor:由于您使用 DI 容器将 UserConfiguration 注册为 Singleton,因此您可以注入此 object 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"
    }
}

However recommended approach to pass application configuration information to services is by using the Options pattern然而,将应用程序配置信息传递给服务的推荐方法是使用选项模式


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

services.AddControllers();

Add then access the configuration option:添加然后访问配置选项:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM