在 asp.net 核心 webapi 中启动时创建连接的最佳方法是什么?

What is the best way to create a connection in startup in asp.net core webapi?

我想使用 JamaaTech Smpp 库创建一个 SmppClient。对于我将创建的客户端,我想收听传入的短信并将短信的正文发送到 rabbitmq 队列。我的问题是: 如何在我的应用程序启动时只创建一个 smppclient 实例,并将其注入其他服务进行操作。

以下是我如何使用 jamaatech 创建我的 smppclient。

private SmppClient CreateSmppClient(ISmppConfiguration config)
    {
        var client = new SmppClient
        {
            Name = config.Name
        };
        //client.SmppEncodingService = new SmppEncodingService(System.Text.Encoding.UTF8);

        client.ConnectionStateChanged += Client_ConnectionStateChanged;
        client.StateChanged += Client_StateChanged;
        client.MessageSent += Client_MessageSent;
        client.MessageDelivered += Client_MessageDelivered;
        client.MessageReceived += Client_MessageReceived;

        var properties = client.Properties;
        properties.SystemID = config.SystemId;// "mysystemid";
        properties.Password = config.Password;// "mypassword";
        properties.Port = config.Port;// 2034; //IP port to use
        properties.Host = config.Host;// "196.23.3.12"; //SMSC host name or IP Address
        properties.SystemType = config.SystemType;// "mysystemtype";
        properties.DefaultServiceType = config.DefaultServiceType;// "mydefaultservicetype";
        properties.DefaultEncoding = config.Encoding;

        //Resume a lost connection after 30 seconds
        client.AutoReconnectDelay = config.AutoReconnectDelay;

        //Send Enquirer Link PDU every 15 seconds
        client.KeepAliveInterval = config.KeepAliveInterval;

        return client;
    }

1- 创建您自己的接口 ISmppClient 和 SmppClient class

2-在startup.cs配置依赖项

services.AddSingleton<IMySmppClient , MySmppClient >();

3- 通过 Constructor 将 IMySmppClient 注入到 classes 中你需要它的地方