2012-07-24 140 views
1

我有一个有趣的问题,它超越了我的C#舒适区。通过使用WsdlImporter和CodeDomProvider类动态检查Web服务WSDL,我可以生成并编译客户端代理代码到程序集到Web服务。这包括声明如下服务客户端类:C#cast泛型类型

public partial class SomeServiceClient : System.ServiceModel.ClientBase<ISomeService>, ISomeService {...} 

注意,客户端类和ISomeService合同名称的名称是动态的 - 我不知道他们提前。我可以实例化这个类动态使用的对象:

string serviceClientName = "SomeServiceClient";// I derive this through some processing of the WSDL 
object client = webServiceAssembly.CreateInstance(serviceClientName , false, System.Reflection.BindingFlags.CreateInstance, null, new object[] { serviceEndpoint.Binding, serviceEndpoint.Address }, System.Globalization.CultureInfo.CurrentCulture, null); 

但是,如果我需要在这个客户端类设置ClientCredentials,那么我可以不知道如何做到这一点。我认为我可以将客户端对象转换为System.ServiceModel.ClientBase泛型类,然后引用ClientCredentials属性。但是,下面的编译但无法在运行:

System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(username, password, domain); 
((System.ServiceModel.ClientBase<IServiceChannel>)client).ClientCredentials.Windows.ClientCredential = networkCredential; 

是否有某种方式来动态指定演员,或者是有一些方法来设置凭据没有这个投?谢谢你的帮助!马丁

+1

可以请你分享你得到的例外吗? – Artak 2012-07-24 03:45:19

+0

恐怕我现在不在我的开发机器中,但是从内存中,异常是这样的:SomeServiceClient不能转换为System.ServiceModel.ClientBase user304582 2012-07-24 04:50:08

+0

嗨 - 这里是异常的确切形式:无法转换类型'SomeServiceClient'的对象以键入'System.ServiceModel.ClientBase'1 [System.ServiceModel.IClientChannel]'。 – user304582 2012-07-24 14:39:12

回答

2

如果您有共享的例外,我们可以帮你更好的帮助,但是这是我猜:

你的类层次结构是这样的:

public interface ISomeService : System.ServiceModel.IServiceChannel 
{ 
    ... 
} 

public class SomeServiceClient : System.ServiceModel.ClientBase<ISomeService> 
{ 
} 

和你想投SomeServiceClientSystem.ServiceModel.ClientBase<IServiceChannel>。可悲的是,你不能那样做,C#4有一个叫做Covariance的特性,它允许上传泛型类型参数,但只适用于接口,不适用于具体的类。

所以其他选项是使用反射:

ClientCredentials cc = (ClientCredentials)client.GetType().GetProperty("ClientCredentials").GetValue(client,null); 
cc.Windows.ClientCredential = networkCredential; 

这应该没有问题的工作(我没有测试过,所以如果它不工作,告诉我的问题,所以我可以修复它) 。

+0

嗨 - 谢谢 - 是的,反思应该这样做。我明天就去试试看,如果有效的话,接受答案吧! – user304582 2012-07-24 07:32:15