将dll加载到另一个域异常中

时间:2013-09-24 06:52:07

标签: c# .net applicationdomain

您好我正在将dll加载到另一个域,它加载到该域时工作正常,但当我想通过代理对象从该域获取一些信息时,它给出了我的例外,下面是审查的代码是否有任何错误的步骤???

 public class AssemblyProxy
    {
        System.Type[] _types;

    public System.Type[] GetTypes() 
    {
        return _types;
    }

    public string FullName { get; set; }

    public void LoadAssembly(string path)
    {
        try
        {
            Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);

            AppDomain TestDomain = AppDomain.CreateDomain("AssemblyDomain", evidence, AppDomain.CurrentDomain.BaseDirectory, System.IO.Path.GetFullPath(path), true);

            Proxy _asmProxy = (Proxy)TestDomain.CreateInstanceFromAndUnwrap(AppDomain.CurrentDomain.BaseDirectory+"Common.dll", typeof(Proxy).FullName);

            _asmProxy.LoadAssembly(path);

            FullName = _asmProxy.FullName;
            _types = _asmProxy.GetTypes(); //Here i got Exception [Can not load file or assembly]

            AppDomain.Unload(TestDomain);
        }
        catch (Exception ex) 
        {

        }

    }

}

class Proxy : MarshalByRefObject
{
    System.Type[] _types;

    public string FullName { get; set; }

    public System.Type[] GetTypes() 
    {
        return _types;                    
    }

    public void LoadAssembly(string path) 
    {
        System.Reflection.Assembly _assembly = System.Reflection.Assembly.Load(System.IO.File.ReadAllBytes(path));
        _types = _assembly.GetTypes();
        FullName = _assembly.FullName;
    }
}

我得到的例外是:

  

无法加载文件或程序集

2 个答案:

答案 0 :(得分:1)

我解决这个问题的方法是调用LoadFrom(不是Load)和 AppDomain的上下文

sDomain = AppDomain.CreateDomain(DOMAIN_NAME);
sDomain.DoCallBack(AppDomainCallback);

// runs in the context of the AppDomain
private void AppDomainCallback()
{
  Assembly assembly = Assembly.LoadFrom(mAssemblyName);
}

答案 1 :(得分:0)

我已经通过阅读以下博客文章解决了这个问题:我的问题是我从新域返回System.Type对象,这是不允许的,你可以从代理对象而不是System.Type对象返回字符串

Link