如何使类成为单例c#

如何使类成为单例c#,c#,asp.net-core,.net-core,C#,Asp.net Core,.net Core,我试图把代码分开。下面的类是标记化/去标记化类,用于将数据作为标记。但当我调用这个类时,我已经传递了所有参数,这个类在解决方案中的任何地方都调用。所以我想让它成为静态的。比如说 Tokenization.Detokenize(reader["UserPhoneNumber"].ToString(), _appSettings.TokenGroup, _appSettings.TokenTemplatePhone, _appSettings.DetokenizeServiceURL, _appSe

我试图把代码分开。下面的类是标记化/去标记化类,用于将数据作为标记。但当我调用这个类时,我已经传递了所有参数,这个类在解决方案中的任何地方都调用。所以我想让它成为静态的。比如说

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;
        }
    }
}
公共类标记化
{
私有静态AuthToken AuthToken=null;
私有静态void GetToken(字符串strBearTokenURL、字符串StrapId、字符串StrapKey)
{
RestClient-tokenClinet=新的RestClient(strBearTokenURL);
tokenClinet.AddDefaultHeader(“应用程序ID”,StrapID);
tokenClinet.AddDefaultHeader(“应用程序密钥”,StrapKey);
tokenClinet.AddDefaultHeader(“apiVersion”、“2”);
AuthToken=tokenClinet.Post(new RestRequest()).Data;
}
私有静态bool IsTokenExpired(字符串strBearTokenURL、字符串StrapId、字符串StrapKey)
{    
if(AuthToken==null)GetToken(strBearTokenURL、StrapId、StrapKey);
System.DateTime dtDateTime=新的日期时间(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
dtDateTime=dtDateTime.AddSeconds(AuthToken.expires_on).ToLocalTime();
返回dtDateTime t.token).FirstOrDefault();
}
捕获(例外情况除外)
{
掷骰子;
}
}
公共静态字符串Detokenize(字符串deTokenData、字符串tokenGroup、字符串tokenTemplate、字符串detokenizeServiceURL、字符串BealerTokenUrl、字符串应用程序ID、字符串应用程序密钥支付)
{
尝试
{
var request=newrestrequest(detokenizeServiceURL,Method.POST);
request.RequestFormat=DataFormat.Json;
列表有效负载=新列表();
Add(new DeTokenProfile(){tokengroup=tokengroup,token=deTokenData,tokentemplate=tokentemplate});
AddJsonBody(有效载荷);
IRestResponse response=RestClientWithAuth(bearertokenul,app_ID,app_KeyPay)。执行(请求);
var responsestatus=response.responsestatus;
返回response.Data.Select(t=>t.Data.FirstOrDefault();
}
捕获(例外情况除外)
{
掷骰子;
}
}
}
您应该试试这个 (重要提示:我不尝试此代码)

公共类标记化
{
私有静态标记化实例=新标记化();
私有AuthToken AuthToken=null;
私有标记化(){}
私有void GetToken(字符串strBearTokenURL、字符串StrapId、字符串StrapKey)
{
RestClient-tokenClinet=新的RestClient(strBearTokenURL);
tokenClinet.AddDefaultHeader(“应用程序ID”,StrapID);
tokenClinet.AddDefaultHeader(“应用程序密钥”,StrapKey);
tokenClinet.AddDefaultHeader(“apiVersion”、“2”);
AuthToken=tokenClinet.Post(new RestRequest()).Data;
}
private bool IsTokenExpired(字符串strBearTokenURL、字符串StrapId、字符串StrapKey)
{    
if(AuthToken==null)GetToken(strBearTokenURL、StrapId、StrapKey);
System.DateTime dtDateTime=新的日期时间(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
dtDateTime=dtDateTime.AddSeconds(AuthToken.expires_on).ToLocalTime();
返回dtDateTime t.token).FirstOrDefault();
}
捕获(例外情况除外)
{
掷骰子;
}
}
公共字符串Detokenize(字符串deTokenData、字符串tokenGroup、字符串tokenTemplate、字符串detokenizeServiceURL、字符串BealerTokenUrl、字符串应用程序ID、字符串应用程序密钥支付)
{
尝试
{
var request=newrestrequest(detokenizeServiceURL,Method.POST);
request.RequestFormat=DataFormat.Json;
列表有效负载=新列表();
Add(new DeTokenProfile(){tokengroup=tokengroup,token=deTokenData,tokentemplate=tokentemplate});
AddJsonBody(有效载荷);
IRestResponse response=RestClientWithAuth(bearertokenul,app_ID,app_KeyPay)。执行(请求);
var responsestatus=response.responsestatus;
返回response.Data.Select(t=>t.Data.FirstOrDefault();
}
捕获(例外情况除外)
{
掷骰子;
}
}
}
使用方法:


Tokenization.Instance.Detokenize()
same like

似乎您想要一些关于如何在实践中实现单例设计模式的实用示例。在您的情况下,如果您想要实现,您可能必须重构代码库。虽然目前成本不大,但从长远来看还是不错的

注意:记住
单例设计模式的主要理念是对象的实例将在生命周期中创建一次。如果你想知道
关于这一点,我建议你


希望这将有助于

提防singleton,它会产生一个隐藏的依赖项,这将导致您的代码在进行单元测试时非常麻烦,将该对象设置为单例没有错,但是如果不将其作为接口注入到库代码中,您的代码就不应该依赖于单例。该方法是否总是从
\u appSettings
传递值?如果是这样,只需将
\u appSettings
传递给您的方法,它就可以获取所需的所有值。您能否解释一下您对代码所做的更改以及原因?否则很难理解。我将去检查如何以线程安全的方式实现singleton。我不更改代码体,但我添加了一个私有构造函数。我把这门课定为单身汉。外部访问使用:私有静态标记化实例=新标记化();外部类不实例化此类,因为:private Tokenization(){}
public class Tokenization
{
    private static Tokenization Instance = new Tokenization();
    private AuthToken AuthToken = null;

    private Tokenization(){}

    private 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 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 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 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 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;
        }
    }
}
//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();
        }
    }