阅读C# generic ClientBase with interface confusion之后,我设法创建了一个Soap Webservice Factory,该工厂简化了我的代码:
private T ClientMaker<TInterface, T>(string username, string password, string address)
where TInterface : class
where T : ClientBase<TInterface>, TInterface
{
var binding = new BasicHttpBinding();
binding.MaxBufferPoolSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;
binding.MaxReceivedMessageSize = int.MaxValue;
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
EndpointAddress ordersEndpoint = new EndpointAddress(address);
T client = Activator.CreateInstance(typeof(T), new object[] { binding, ordersEndpoint }) as T;
client.ClientCredentials.UserName.UserName = username;
client.ClientCredentials.UserName.Password = password;
return client;
}
和这样使用:
var client = ClientMaker<CreateWebOrder.WEB_Functions_Port, CreateWebOrder.WEB_Functions_PortClient>(user, pass, endpointBase + "Codeunit/WEB_Functions");
CreateWebOrder.WEB_Functions_Port is the interface implemented by CreateWebOrder.WEB_Functions_PortClient
我不太喜欢的一件事是,我需要提供接口和Web服务的类/类型,所以我想知道是否有办法通过从类型参数。
考虑到返回类型为ClientBase,并且由于提供的类型参数而已知TInterface,为什么然后需要提供“ PortClient”?
理想情况下,我只想使用1个类型参数来致电工厂,但我不知道是否可能
首先,您需要清理签名。减少参数量。以《清洁代码》一书为参考,一个参数已经是一个参数太多了。如果您可以实现控制反转,那么这很有意义,但实际上在这种情况下,这仅意味着创建POCO / DTO / Class来传递数据。满足开放/封闭原则