如何为从nuget引用的库创建Singleton实例

时间:2019-03-13 15:13:27

标签: c# singleton

任务是多次调用第三方服务/包装并获得响应。下面是示例代码,我试图弄清楚如何为服务创建单例实例。

class Program
{
    static void Main(string[] args)
    {

        List<string> trips = new List<string>();
        trips.Add("ABC");
        trips.Add("XYZ");
        foreach (string s in trips) {
            Test.TestMethod(s);
        }
    }
}

public static class Test
{
    public static bool TestMethod(string trip)
    {
        BridgeApiClient bridgeApiClient = new BridgeApiClient("http://localhost/Service.svc", "username", "password");
        TripRequest tr = new TripRequest();
        tr.TripNumber = trip;

        var response = bridgeApiClient.GetTrip(tr);

        return true;
    }
}

1 个答案:

答案 0 :(得分:1)

您只需声明一个static成员变量并使用它即可:

public static class Test
{
    private static readonly BridgeApiClient bridgeApiClient = new BridgeApiClient("http://localhost/Service.svc", "username", "password");

    public static bool TestMethod(string trip)
    {
        TripRequest tr = new TripRequest();
        tr.TripNumber = trip;
        var response = bridgeApiClient.GetTrip(tr);
        return true;
    }
}