0

Note that this similar sounding question does not in fact answer my question.

I have a class which involves reading a message from a queue and processing it. I was trying to use a method in another class to handle it, and couldn't manage it without making it static, and wondered what the best way to do this would be.

So this is the code with the HandleMessage in the same class:

 myconfigclass {
       protected override void DoConfigure(IDependancyInjectionContainer container)
       {
           IServiceInformation serviceDetail = m_ServiceDiscovery.GetServiceEndpoint("rabbitmq").Result;
            string rabbitMqAddress = $"{serviceDetail.IpAddress}:{serviceDetail.Port}";
            RabbitMqServer mqServer = new RabbitMqServer(rabbitMqAddress);


            mqServer.RegisterHandler<CdsGatewayMessage>(HandleMessage); //want HandleMessage to be in another class
            mqServer.Start();

       }

       public object HandleMessage(IMessage<CdsGatewayMessage> message)
      {//does stuff with the message
      }

What I want to do is to move HandleMessage into another class MessageProcessor, but I can only get this to work by making MessageProcessor.HandleMessage() static.

Is there a simple way to get this to work in an external class as an instance?

jazza1000
  • 4,099
  • 3
  • 44
  • 65
  • You want simple or best way? – bot_insane Apr 20 '18 at 12:31
  • I will take either – jazza1000 Apr 20 '18 at 12:33
  • It is defintely a good idea to avoid static. In most cases static fields should be avoided as much as a naked goto. On partial solution I used was this: I have a class that needs instantiation. Then I create and assign a instance to a static variable. I get the advantages of Static, without the issues of having written something only existing as static. – Christopher Apr 20 '18 at 12:33
  • What happened when you made the other class non-static? Are you saying you can not create an instance of that class and then pass the method? `MessageProcessor processor = new MessageProcessor(); mqServer.RegisterHandler(HandleMessage);` – Taylor Fraley Apr 21 '18 at 20:41
  • I don't kniw what it is you are trying to ultimately accomplish – theMayer Apr 21 '18 at 21:29

0 Answers0