How to avoid unnecessary objects getting initialized WCF

40 Views Asked by At

We have a WCF service exposing several operations with BasicHttpBinding and the service implementation is some thing like this

Public Class MyService
{

  private IHandler1 _handler1 = GetHandler1();
  private IHandler2 _handler1 = GetHandler12();
  private IHandler3 _handler1 = GetHandler3();


Public Void HandleMessage(string msg)
{
  _handler1.SomeMethod();
}



Public Void HandleMessage(string msg)
{
  _handler1.SomeMethod();
}
Public Void HandleMessage2(string msg)
{
  _handler2.SomeMethod();
}

Public Void HandleMessage2(string msg)
{
  _handler3.SomeMethod();
}



}

But the issue I see with this code, that all the handlers are getting initialized i.e handler1/2/3 even when we receive a request to handle one of the messages i mean when the client calls HandleMmessage2() method only the handler _handler2 should be intialized. What is the best way to achieve this.?

Since the service is exposing endpoint with BasicHttpbinding which doesn't support Sessions InstanceContextMode will be PerCall which creates all the handlers even when not required for evert request from client.

1

There are 1 best solutions below

1
On

Maybe I'm misunderstanding something, but why not create the handlers in the method they're needed by? Then your implementation would look something like this:

public class MyService
{

    public void HandleMessage(string msg)
    {

        IHandler1 _handler = GetHandler1();   
        _handler.SomeMethod();
    }

    public void HandleMessage2(string msg)
    {
        IHandler2 _handler = GetHandler();
        _handler.SomeMethod();
    }

    public void HandleMessage3(string msg)
    {

        IHandler3 _handler = GetHandler3();
        _handler.SomeMethod();
    }
}