【问题标题】:What is the best way to create a connection in startup in asp.net core webapi?在 asp.net core webapi 的启动中创建连接的最佳方法是什么?
【发布时间】:2020-03-25 08:20:36
【问题描述】:

我想使用 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;
    }

【问题讨论】:

  • IMO 没有有意义的方式通过无状态 Web api直接在 asp.net 中提供有状态连接服务的实例。编写一个永久运行并保持该连接打开的后端服务;或更好:即时连接并在请求后立即断开连接。除非连接和断开连接非常昂贵,否则这是通常的方法。
  • 后端服务?喜欢 dotnet 上的后台服务?

标签: c# asp.net-core dependency-injection asp.net-core-webapi smpp


【解决方案1】:

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

2-在startup.cs中配置依赖

services.AddSingleton<IMySmppClient , MySmppClient >();

3- 将 IMySmppClient 由 Contructor 注入到你需要的类中

【讨论】:

  • 我已经这样做了。这是具有单例生命周期的简单依赖注入。我希望我的应用程序在启动时创建一个 MySmppClient 实例,并且能够在其他类中使用该实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
相关资源
最近更新 更多