[英]Creating a local instance of an object being referenced from the AppDomain
我試圖找出是否有辦法創建我的對象的本地實例從app域引用,原因是由於我在方法的所有執行過程中獲得了大量的聊天。 因此,我不必一直調用遠程對象,而只是調用在方法內創建的本地實例。
我一直在關注RemotingServices Marshal和GetObjectData方法,但一直無法弄清楚它們是否會起作用,谷歌也沒有幫助
所以類定義如下所示
[XmlRoot("SI")]
public class SI : MarshalByRefObject, IXmlSerializable
然后運行時類的實例看起來像這樣。
Name: Service
Value: {System.Runtime.Remoting.Proxies.__TransparentProxy}
Type: SI {System.Runtime.Remoting.Proxies.__TransparentProxy}
我希望按照以下方式完成我所需要的工作
var uri =RemotingServices.GetObjectUri(Service);
var serv = RemotingServices.Marshal(Service, uri, typeof(SI)); //Service is the object I described above
SerializationInfo info = new SerializationInfo(typeof(SI), new FormatterConverter());
StreamingContext context = new StreamingContext(StreamingContextStates.All);
serv.GetObjectData(info, context);
var t2 = serv.GetRealObject(context);
調用GetRealObject時出現以下錯誤“嘗試讀取或寫入受保護的內存。這通常表示其他內存已損壞。”
我還沒有找到任何方法來實現這一點,任何人都可能有一些建議嗎?
好的。 因此要么安裝Unity,要么創建自己的資源定位器(對象字典)。
以下是我寫的資源定位器:
using System;
using System.Collections.Generic;
namespace Bizmonger.Client.Infrastructure
{
public class ServiceLocator
{
#region Members
Dictionary<Type, object> _dictionary = new Dictionary<Type, object>();
static ServiceLocator _serviceLocator = null;
#endregion
public static ServiceLocator Instance
{
get
{
if (_serviceLocator == null)
{
_serviceLocator = new ServiceLocator();
}
return _serviceLocator;
}
}
public object this[Type key]
{
get
{
if (!_dictionary.ContainsKey(key))
{
_dictionary.Add(key, Activator.CreateInstance(key));
}
return _dictionary[key];
}
set
{
_dictionary[key] = value;
}
}
public bool ContainsKey(Type type)
{
return _dictionary.ContainsKey(type);
}
public void Load(object data)
{
if (data == null) { return; }
RemoveExisting(data);
_dictionary.Add(data.GetType(), data);
}
public void Load(Type type, object data)
{
if (data == null) { return; }
RemoveExisting(data);
_dictionary.Add(type, data);
}
#region Helpers
private void RemoveExisting(object data)
{
bool found = _dictionary.ContainsKey(data.GetType());
if (found)
{
_dictionary.Remove(data.GetType());
}
}
#endregion
}
}
然后你可以在你的客戶端做到這一點:
var uri =RemotingServices.GetObjectUri(Service);
var serv = RemotingServices.Marshal(Service, uri, typeof(SI));
ServiceLocator.Instance.Load(serv);
您可以像這樣檢索此對象:
var server = ServiceLocator.Instance[typeof(some_class)] as some_class;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.