简体   繁体   English

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

[英]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: 您可以只声明一个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;
    }
}

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

相关问题 如何从引用的NuGet程序包中正确选择程序集? - How do I properly choose assemblies from referenced NuGet packages? 如何建立清单 <T> 从手动引用的DLL中的类的实例? - How do I create a List<T> from an instance of a class from a manually referenced DLL? 为引用的装配创建单例 - Create a singleton for referenced assembly 如何为实现它而创建单例实例? - How can I create an instance of a singleton just for the purpose of implementing it? 如何使我的构建将内容从引用的库复制到IIS express文件夹? - How do I make my build copy content from a referenced library to IIS express folder? 如何从类库项目和预编译视图创建NuGet包? - How to create NuGet package from class library projects and precompiled views? 我如何引用我在 HostBuilder 中添加的 singleton 实例,作为我定义的 Scoped 实例的一部分? - How do i reference a singleton instance i'm adding in the HostBuilder, as a part of a Scoped instance i'm defining? 使用 IServiceProvider 从 singleton 实例创建 scope - Create scope using IServiceProvider from singleton instance 如何从命令行创建nugetpackages.config文件? - How do I create a nuget packages.config file from the command line? 如何在C#中从字符串创建实例? - How do I create an instance from a string in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM