gpt4 book ai didi

c# - 创建从 AppDomain 引用的对象的本地实例

转载 作者:行者123 更新时间:2023-11-30 18:28:29 24 4
gpt4 key购买 nike

我试图找出是否有一种方法可以创建从应用程序域引用的对象的本地实例,这是因为在该方法的所有执行过程中我收到了大量的喋喋不休.因此,不必一直调用远程对象,我只想调用在方法内创建的本地实例。

我一直在研究 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 时出现以下错误“试图读取或写入 protected 内存。这通常表明其他内存已损坏。”

我还没有找到任何方法来实现这个,有人可能有一些建议吗?

最佳答案

好的。因此,要么安装 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;

关于c# - 创建从 AppDomain 引用的对象的本地实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24997533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com