简体   繁体   中英

How do I create Singleton instance for a library referenced from nuget

Task is to call a third party service/wrapper multiple times and get the response. Below is the sample code and I am trying to figured out how to create singleton instance for the service.

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

You can just declare a static member variable and use that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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