首页 > 解决方案 > 如何将类设为单例 C#

问题描述

我正在尝试将代码分开。下面的类是标记化/去标记化类,用于将数据作为标记。但是当我调用这个类时,我已经传递了所有参数,这个类在解决方案中随处调用。所以我想制作成静态的。例如

Tokenization.Detokenize(reader["UserPhoneNumber"].ToString(), _appSettings.TokenGroup, _appSettings.TokenTemplatePhone, _appSettings.DetokenizeServiceURL, _appSettings.BearerTokenGeneratorURL, _appSettings.App_IDPayLoad, _appSettings.App_KeyPayLoad);

所以我只想通过

Tokenization.Detokenize(reader["UserPhoneNumber"].ToString(), _appSettings.TokenGroup, _appSettings.TokenTemplatePhone)

基本上我想将静态块和 tokenizae/detokenizae 方法分开。所以看起来不错。我怎么能这样做?

 public  class Tokenization
{


    private static AuthToken AuthToken = null;

    private static void GetToken(string strBearTokenURL, string strAppid, string strAppkey)
    {
        RestClient tokenClinet = new RestClient(strBearTokenURL);
        tokenClinet.AddDefaultHeader("App_ID", strAppid);
        tokenClinet.AddDefaultHeader("App_Key", strAppkey);
        tokenClinet.AddDefaultHeader("apiVersion", "2");
        AuthToken = tokenClinet.Post<AuthToken>(new RestRequest()).Data;
    }

    private static bool IsTokenExpired(string strBearTokenURL, string strAppid, string strAppkey)
    {    
        if (AuthToken == null) GetToken( strBearTokenURL, strAppid, strAppkey);
        System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
        dtDateTime = dtDateTime.AddSeconds(AuthToken.expires_on).ToLocalTime();
        return dtDateTime <= DateTime.Now;
    }


    public static RestClient RestClientWithAuth(string strBearTokenURL, string strAppid, string strAppkey)
    {
        try
        {
            RestClient clinet = new RestClient();
            if (IsTokenExpired(strBearTokenURL, strAppid, strAppkey)) GetToken(strBearTokenURL, strAppid, strAppkey);
            clinet.AddDefaultHeader("Authorization", "Bearer " + AuthToken.access_token);
            return clinet;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }




    public static string Tokenize(string tokenData, string tokenGroup, string tokenTemplate, string tokenizeServiceURL, string bearerTokenURL, string app_ID, string app_Key)
    {
        try
        {                    
            var request = new RestRequest(tokenizeServiceURL, Method.POST);
            request.RequestFormat = DataFormat.Json;
            List<TokenProfile> payLoad = new List<TokenProfile>();               

            payLoad.Add(new TokenProfile() { tokengroup = tokenGroup, data= tokenData, tokentemplate = tokenTemplate });                

            request.AddJsonBody(payLoad);
            // execute the request
            IRestResponse<List<TokenResponse>> response = RestClientWithAuth(bearerTokenURL, app_ID, app_Key).Execute<List<TokenResponse>>(request);
            var responsestatus = response.ResponseStatus;
            return response.Data.Select(t => t.token).FirstOrDefault();
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }



    public static string Detokenize(string deTokenData, string tokenGroup, string tokenTemplate, string detokenizeServiceURL, string bearerTokenURL, string app_ID, string app_KeyPay)
    {
        try
        {
            var request = new RestRequest(detokenizeServiceURL, Method.POST);
            request.RequestFormat = DataFormat.Json;
            List<DeTokenProfile> payLoad = new List<DeTokenProfile>();                
            payLoad.Add(new DeTokenProfile() { tokengroup = tokenGroup, token = deTokenData, tokentemplate = tokenTemplate });
            request.AddJsonBody(payLoad);
            IRestResponse<List<DeTokenResponse>> response = RestClientWithAuth(bearerTokenURL, app_ID, app_KeyPay).Execute<List<DeTokenResponse>>(request);
            var responsestatus = response.ResponseStatus;
            return response.Data.Select(t => t.data).FirstOrDefault();
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }
}

标签: c#asp.net-core.net-core

解决方案


似乎您希望有一些实际示例来说明如何在实践中实现单例设计模式。在您的情况下,如果您想实现,您可能必须重构您的代码库。虽然目前它的成本不高,但从长远来看它会很好。

注意:请记住,对象的主要理念Singleton design pattern是一生中将创建一次。如果您想了解更多关于此的信息,我建议您参考此文档此文档

//Interface declaration
    public interface ITokennization
    {
        object TokenizationClassMethod();
    }

    //Interface Inheritance/Implementation in class 
    public class TokenizationClass : ITokennization
    {

        private static TokenizationClass _singletonInstance;

        private static readonly object padlock = new object();

        //Default constructor
        public TokenizationClass()
        {

        }
        // SingleTon Design Pattern 
        public static TokenizationClass CheckSingleInstance()
        {
            if (_singletonInstance == null)
            {
                lock (padlock)
                {
                    //Checks instance each time 
                    if (_singletonInstance == null)
                        //creates  new instance if no instances already created
                        _singletonInstance = new TokenizationClass();
                }
            }

            return _singletonInstance;
        }
        // Class Method
        public object TokenizationClassMethod()
        {
            throw new NotImplementedException();
        }
    }

希望这会有所帮助


推荐阅读