lukevp / ESC-POS-.NET

Efficient, Easy to Use Thermal Printing & POS (Windows/Linux/OSX, WiFi/BT/USB/Ethernet)
MIT License
503 stars 166 forks source link

Using the library in Asp.net core webapi does not print or has huge delay => use singleton for printers instances #176

Closed cyberdarius closed 2 years ago

cyberdarius commented 2 years ago

Just to let everyone facing this issue:

I used the library (2.0.0.0) in a ASP.NET CORE WebApi application (Network Printer):

A. If used in a standard asp.net core DI way (scoped/transient injected instance), the library does not print or print with huge delay.

The solution was to hold the printers instances in a Singleton (only the printers instances), and retrieving the printer instance needed from the service in charge to print (scoped/transient).

Like @gusVLZ suggested here https://github.com/lukevp/ESC-POS-.NET/issues/169


B. On the same webapi, I created 2 different singleton instances of the same network printer (same ip and port) the first instance print correctly every time. The second never print OR print with huge delay OR print when I terminate the webapi.

Something like described here. https://github.com/lukevp/ESC-POS-.NET/issues/174


Similar to B:

If I create a new instance (NetworkPrinter) and print.Write() it works. But if I dispose and recreate the instance it does not print OR print with huge delay OR print when I terminate the webapi.

someting like :

var prn = new NetworkPrinter(settings: new NetworkPrinterSettings() { ConnectionString = "192.168.1.10:9100" }); prn.write( .....) // print ok.

prn.Dispose(); prn = new NetworkPrinter(settings: new NetworkPrinterSettings() { ConnectionString = "192.168.1.10:9100" }); prn.write( .....) // does not print OR print with huge delay OR print when I terminate the webapi.

lukevp commented 2 years ago

@cyberdarius,

The NetworkPrinter is meant to be a digital twin/singleton, and only have a single instance per logical connection (IP/Port combo). This library was primarily built to run within a standalone POS as a background application, so this use case wasn't really tested, but it definitely should be supported. The reason this happens is because the library connects to the printer continuously and maintains status information of the printer. However, it does sound like there's an issue with the dispose and closing the underlying TCP connections. My recommendation is for there to be a separate NetworkPrinter that doesn't maintain a persistent connection and can be used for singleton writes like this.

cyberdarius commented 2 years ago

Understood. Thanks