假设我在我的客户端应用程序中有一个名为 DataService
的类。这个类有许多方法,这些方法调用了一个 WCF 服务。
我想知道哪种做法更好:
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(); ... } }
client
在方法调用本身中有依赖项,我可能会使用 Autofac 的“Function”(有效地是隐式工厂)方法。 - user2246674