.net core 2.0學習筆記(六):Remoting核心類庫RealProxy遷移
在學習.net core的過程中,我們已經明確被告知,Remoting將不會被支持。官方的解釋是,.net framework 類型包含了太多的Runtime的內容,是一個非常重量級的服務實現,已被確定為一項有問題的體系結構。說白了就是遷移的難度很大,.net core中直接不提供了。微軟的建議是,如果是進程內或跨進程通訊,建議我們使用 Pipes或者內存映射文件(Memory Mapped Files)。如果是機器間的調用,建議我們采用網絡通訊的方案,比如HTTP、WCF等。
好吧,既然微軟官方不支持, 我們只能自己想辦法搞定了。
OK,說遷移方案前,我們先看看.net Framework中,使用Remoting的代碼:
通過Remoting封裝後的服務調用方法,我們可以直接得到一個服務接口的實現,通過調用次接口的本地代理實現執行遠程調用。
static void Main(string[] args)
{
IUserService service = InvokeSerice.Proxy<IUserService>();
string uName = service.GetCurrentUserName();Console.WriteLine($"當前用戶名:{uName}");
Console.ReadLine();
}
IUserService接口的聲明如下:
public interface IUserService
{
string GetCurrentUserName();
}
InvokeService方法的核心實現邏輯如下:
//遠程調用服務提供類
public class InvokeService
{//獲取一個服務的本地調用代理對象
public static T Proxy<T>()
{
var proxy = new InvokeProxy<T>();
return (T)proxy.GetTransparentProxy();
}
}
//服務本地代理對象實現類
public class InvokeProxy<T> : RealProxy
{
private Type type = null;
public InvokeProxy() : this(typeof(T))
{
type = typeof(T);
}protected InvokeProxy(Type classToProxy) : base(classToProxy)
{
}//接收本地調用請求,然後轉發遠程訪問
public override IMessage Invoke(IMessage msg)
{
Console.WriteLine("Invoke 遠程服務調用!");
ReturnMessage message = new System.Runtime.Remoting.Messaging.ReturnMessage("Test",null,0,null,(IMethodCallMessage)msg);return (IMessage)message;
}
}
通過.NET Portability Analyzer分析這個工程,我們會得到系統不支持的結果。
既然,.net core 已經不支持RealProxy,那麽就只能另起爐竈了。通過翻閱.net core的代碼,終於發現了一個程序集:System.Reflection.DispatchProxy。此程序中,有一個類型DispatchProxy。(靈感還是來自於WCF。WCF是.net 中重量級的API,微軟不可能不支持,通過翻閱其中的實現邏輯,終於到了RealProxy的替代方案。)
好吧,通過DispatchProxy提供的功能,很容易可以替代RealProxyP,Remoting的問題終於比較完美的解決了。下面就貼一下替換後的服務實現代碼吧。
public class InvokeSerice
{
public static T Proxy<T>()
{
return DispatchProxy.Create<T, InvokeProxy<T>>();
}
}public class InvokeProxy<T> : DispatchProxy
{
private Type type = null;
public InvokeProxy()
{
type = typeof(T);
}protected override object Invoke(MethodInfo targetMethod, object[] args)
{
Console.WriteLine("Invoke 遠程服務調用!");return "Test";
}
}
.net core 2.0學習筆記(六):Remoting核心類庫RealProxy遷移