Which is better, one client instance for the class or one in each method?

Say that I have a class called DataService in my client application. This class has many methods that make calls to the WCF service.

I wonder which one is better:

  • To create an instance of WebServiceClient in a class that is initialized when the class is instantiated and used by these methods, for example:

     public class DataService { MyWebServiceClient client = new MyWebServiceClient(); public void Method1() { var v = client.Operation1(); ... } public void Method2() { var v = client.Operation2(); ... } } 
  • Or, to create and initialize an instance of WebServiceClient in each class method, for example:

     public class DataService { public void Method1() { var client = new MyWebServiceClient(); var v = client.Operation1(); ... } public void Method2() { var client = new MyWebServiceClient(); var v = client.Operation2(); ... } } 
  • There is also a third option, which is to declare in the class and initialize in each method:

     public class DataService { MyWebServiceClient client; public void Method1() { client = new MyWebServiceClient(); var v = client.Operation1(); ... } public void Method2() { client = new MyWebServiceClient(); var v = client.Operation2(); ... } } 
+4
source share
3 answers

If you have a dependency on another class like this, it is usually recommended to separate its construction and pass it (or perhaps use dependency injection). This makes it easier to test your DataService class, you can more easily mock your WebServiceClient this way.

consider something like ...

 public class DataService { public DataService(MyWebServiceClient client) { .... //Assign it to a private var... } } 
+8
source

I would use constructor injection and one instance for each class, as in:

 public class DataService { IMyWebServiceClient _client; public DataService(IMyWebServiceClient client) { _client=client } public DataService():this(new MyWebServiceClient()) { } public void Method1() { var v = _client.Operation1(); ... } public void Method2() { var v = _client.Operation2(); ... } } 
+1
source

I used method 3 most often in older applications. But recently, some code has appeared in which you have an object declaration, but creating an instance is done using some kind of structure, for example Spring. The instance is stored inside the container. However, learning about this process.

 public class DataService { MyWebServiceClient client; public void Method1() { var v = client.Operation1(); ... } public void Method2() { var v = client.Operation2(); ... } } 
0
source

Source: https://habr.com/ru/post/1492806/


All Articles