Let's say that I have a class called DataService
in my client app. This class have many methods which make calls to a WCF service.
I wonder which is a better practice:
To create an instance of WebServiceClient in the class, which is initialized when an instance of the class is created, and is used by the methods, e.g:
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 method of the class, e.g:
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 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();
...
}
}
When you have a dependency on another class like this, its usually a good idea to separate out its construction and pass it in (or possibly use dependency injection). This makes your DataService class easier to test, 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...
}
}
I would use Constructor injection and one instance per 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();
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With