Search code examples
c#wpfazure-service-fabric

ServiceFabric communication with local WPF App


Is there any way to connect Service Fabric Stateless service (in local) to my local WPF app? I would like to process some data on stateless service and send update to WPF app for example using NServiceBus


Solution

  • Yes, you can use a message queue for this.

    Your stateless service would create a message and put it on the queue:

        static async Task SendMessageAsync()
        {
            // create a Service Bus client 
            await using (ServiceBusClient client = new ServiceBusClient(connectionString))
            {
                // create a sender for the queue 
                ServiceBusSender sender = client.CreateSender(queueName);
    
                // create a message that we can send
                ServiceBusMessage message = new ServiceBusMessage("Hello world!");
    
                // send the message
                await sender.SendMessageAsync(message);
                Console.WriteLine($"Sent a single message to the queue: {queueName}");
            }
        }
    

    The WPF application would receive that message and process it:

        // handle received messages
        static async Task MessageHandler(ProcessMessageEventArgs args)
        {
            string body = args.Message.Body.ToString();
            // update the ViewModel here
    
            // complete the message. messages is deleted from the queue. 
            await args.CompleteMessageAsync(args.Message);
        }
    

    Instead of sending a simple string, I recommend sending a serialized object, e.g. using JSON.

    More info here: link and here: link