我有一個.NET應用程序,其中獨立AppDomain中的程序集必須共享按值傳遞的序列化對象。如何在兩個.NET AppDomains之間傳遞未知類型?
兩個組件引用共享組件定義的基類的服務器類,並且還定義了用於將域之間傳遞的entiy類型的基類:
public abstract class ServerBase : MarshalByRefObject
{
public abstract EntityBase GetEntity();
}
[Serializable]
public abstract class EntityBase
{
}
服務器組件限定服務器類和實體類型的具體implemetation:
public class Server : ServerBase
{
public override EntityBase GetEntity()
{
return new EntityItem();
}
}
[Serializable]
public class EntityItem : EntityBase
{
}
客戶端組件創建AppDomain
其中服務器組件將被託管並使用服務器類的實例來請求具體實例實體類型:
class Program
{
static void Main()
{
var domain = AppDomain.CreateDomain("Server");
var server = (ServerBase)Activator.CreateInstanceFrom(
domain,
@"..\..\..\Server\bin\Debug\Server.dll",
"Server.Server").Unwrap();
var entity = server.GetEntity();
}
}
Unfortnately,這種方法失敗了SerializationException
,因爲客戶端組件具有被返回的具體類型沒有直接的知識。
我讀過.NET遠程處理在使用二進制序列化時支持未知類型,但我不確定這是否適用於我的設置或如何配置它。
另外,是否有任何其他方式將未知的具體類型從服務器傳遞到客戶端,因爲客戶端只需要通過其已知的基類接口訪問它。
謝謝你的建議,
添
編輯:
按照要求由漢斯,這裏是異常消息和堆棧跟蹤。
SerializationException
Type is not resolved for member 'Server.EntityItem,Server, Version=1.0.0.0,Culture=neutral, PublicKeyToken=null'.
at Interop.ServerBase.GetEntity()
at Client.Program.Main() in C:\Users\Tim\Visual Studio .Net\Solutions\MEF Testbed\Client\Program.cs:line 12
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
感謝漢斯。您的建議非常合理,但我需要確保它不會引入額外的問題。我所描述的是沙箱方案的一部分,所以我不希望CLR將未知程序集加載到主AppDomain(它具有更廣泛的權限),如果它可能會危及安全。你有看法嗎?再次感謝。 – 2010-11-15 15:47:13
使用一個接口,在其自己的程序集中聲明並由兩者引用。 – 2010-11-15 16:12:21
好吧,我改變了EntityBase類作爲一個接口,它和以前一樣,駐留在共享程序集中,但是異常仍然被拋出(可能是因爲你已經聲明 - 傳遞的對象是未知的客戶)。 – 2010-11-15 16:39:11