萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

.NET 動態編譯與 Web Service 動態代理呼叫完整實作

核心架構

  1. 動態編譯:CodeDomProvider + CompilerParameters 將字串原始碼編譯為記憶體組件。
  2. 動態產生 WCF Client Proxy 類別原始碼。
  3. 反射實例化 Proxy 並呼叫服務方法。

1. 服務參數定義類別

public class WsCallParameters
{
    public string ServiceAddress { get; set; }      // Endpoint Address
    public string ServiceNamespace { get; set; }    // Contract Namespace
    public string MethodName { get; set; }          // Operation Name
    public string MethodAction { get; set; }        // SoapAction
    public string MethodReplyAction { get; set; }   // ReplyAction
    public string ReturnType { get; set; }          // 回傳型別全名 (如 System.String)
}

2. 動態產生 Proxy 原始碼

public class DynamicProxyGenerator
{
    public string GenerateProxyCode(WsCallParameters p)
    {
        var sb = new StringBuilder();
        sb.AppendLine("using System;");
        sb.AppendLine("using System.ServiceModel;");
        sb.AppendLine("using System.ServiceModel.Channels;");
        sb.AppendLine();
        sb.AppendLine($"namespace DynamicProxy {{");
        sb.AppendLine($"  [ServiceContract(Namespace=\"{p.ServiceNamespace}\")]");
        sb.AppendLine($"  public interface I{p.MethodName}Contract {{");
        sb.AppendLine($"    [OperationContract(Action=\"{p.MethodAction}\", ReplyAction=\"{p.MethodReplyAction}\")]");
        sb.AppendLine($"    {p.ReturnType} {p.MethodName}();");
        sb.AppendLine($"  }}");
        sb.AppendLine();
        sb.AppendLine($"  public class {p.MethodName}Client : ClientBase<I{p.MethodName}Contract>, I{p.MethodName}Contract {{");
        sb.AppendLine($"    public {p.MethodName}Client(Binding binding, EndpointAddress address) : base(binding, address) {{ }}");
        sb.AppendLine($"    public {p.ReturnType} {p.MethodName}() => Channel.{p.MethodName}();");
        sb.AppendLine($"  }}");
        sb.AppendLine("}");
        return sb.ToString();
    }
}

3. 動態編譯與呼叫

public class DynamicWsInvoker
{
    public object Invoke(WsCallParameters parameters)
    {
        // 1. 產生原始碼
        string code = new DynamicProxyGenerator().GenerateProxyCode(parameters);

        // 2. 編譯
        var provider = CodeDomProvider.CreateProvider("CSharp");
        var cp = new CompilerParameters
        {
            GenerateExecutable = false,
            GenerateInMemory = true,
            TreatWarningsAsErrors = false
        };
        cp.ReferencedAssemblies.Add("System.dll");
        cp.ReferencedAssemblies.Add("System.ServiceModel.dll");
        cp.ReferencedAssemblies.Add("System.Runtime.Serialization.dll");

        CompilerResults results = provider.CompileAssemblyFromSource(cp, code);
        if (results.Errors.HasErrors)
        {
            var err = string.Join("\n", results.Errors.Cast().Select(e => e.ErrorText));
            throw new InvalidOperationException("動態編譯失敗:\n" + err);
        }

        // 3. 反射建立 Client 並呼叫
        Assembly asm = results.CompiledAssembly;
        Type clientType = asm.GetType($"DynamicProxy.{parameters.MethodName}Client");
        var binding = new BasicHttpBinding(); // 或依需求 WSHttpBinding 等
        var address = new EndpointAddress(parameters.ServiceAddress);

        var ctor = clientType.GetConstructor(new[] { typeof(Binding), typeof(EndpointAddress) });
        object client = ctor.Invoke(new object[] { binding, address });

        MethodInfo method = clientType.GetMethod(parameters.MethodName);
        return method.Invoke(client, null);
    }
}

4. 使用範例

var param = new WsCallParameters
{
    ServiceAddress = "https://localhost:8080/MyService",
    ServiceNamespace = "https://tempuri.org/",
    MethodName = "GetData",
    MethodAction = "https://tempuri.org/IMyService/GetData",
    MethodReplyAction = "https://tempuri.org/IMyService/GetDataResponse",
    ReturnType = "System.String"
};

string result = (string)new DynamicWsInvoker().Invoke(param);
Console.WriteLine(result);

進階擴充

  • 支援方法參數:在產生介面時加入參數定義,並透過 MethodInfo.Invoke(client, args) 傳入。
  • 快取編譯組件:以 (ServiceAddress, MethodName) 為 Key 避免重複編譯。
  • 支援 async/await:產生 Task<T> 回傳型別的非同步方法。
  • 安全性:BasicHttpBinding 預設無加密,生產環境請改用 WSHttpBinding + 憑證/Windows 驗證。

適用場景

  • 服務端點/合約在執行期才決定 (多租戶、插件架構)。
  • 避免專案加入 Service Reference 造成版本綁定。
  • 測試工具、通用整合平台動態呼叫異構 Web Service。
copyright © 萬盛學電腦網 all rights reserved