【问题标题】:How to call static methods in assembly inside AppDomain [duplicate]如何在 AppDomain 内的程序集中调用静态方法 [重复]
【发布时间】:2015-04-30 02:55:36
【问题描述】:

我有以下课程(为便于阅读而缩短)

public class Connection
{
    Guid _id;
    AppDomain _appDomain;
    Type _coreApp;

    public string ConnectionName
    {
        get
        {
            this._coreApp.InvokeMember("_some_property_", BindingFlags.GetProperty, null, null, null).ToString();
        }
    }

    public Connection(string username, string password)
    {
        this._id = Guid.NewGuid();
        this._appDomain = AppDomain.CreateDomain(this._id.ToString());
        Assembly asm = this._appDomain.Load("_some_dll_");
        this._coreApp = asm.GetExportedTypes().First(t => t.Name == "_some_type_");
        this._coreApp.InvokeMember("_some_method_", BindingFlags.InvokeMethod, null, null, new object[] { username, password });
    } 
}

我也有以下代码

public class Main()
{
    public Main()
    {
        Connection connOne = new Connection("_some_user_1_", "_some_pw_1_");
        Connection connTwo = new Connection("_some_user_2_", "_some_pw_2_");

        string nameOne = connOne.ConnectionName;
        string nameTwo = connTwo.ConnectionName;
    }
}

我也得到了这些事实:

  • 我加载到 AppDomain 的 dll 是第 3 方
  • _some_method_ 和 _some_property_ 是静态的
  • ConnectionName 应该为两个实例返回不同的值,因为参数不相同。

最后我遇到了这个问题:

我的工作假设是从它自己的 AppDomain 中的 DLL 中的类型调用静态方法,会将该调用与其他人隔离到单独 AppDomain 中同一 DLL 中的同一静态方法,但出于某种原因,这不是这样。例如,如果我像这样运行代码,我会将两个字符串都设为“result_1”,反转参数会将两个字符串都设置为“result_2”。

我基本上需要完全隔离 Connection 的每个实例上的 dll,因为有很多静态的事情正在发生,我不能像这种情况那样让一个改变另一个。

我不确定代码是否可以编译,请忽略任何语法或语义问题,因为我无法发布实际代码,必须在浏览器上即时编写。

【问题讨论】:

  • 您能说明您将类型加载到单独的 AppDomain 的位置吗?
  • 这行不是 this._appDomain = AppDomain.CreateDomain(this._id.ToString()); 为该 Connection 实例创建一个 AppDomain我>?然后是不是 this._coreApp = asm.GetExportedTypes().First(t => t.Name == "_some_type");_ 从 THAT AppDomain 实例化一个类型?
  • 抱歉,深夜扫描时错过了这些行。
  • @RonBeyer 随时添加该评论作为答案,因为我在那里找到了我想要的东西,谢谢。

标签: c# .net runtime appdomain


【解决方案1】:

我同意@RonBeyer。您的所有代码和方法/属性调用都在与 Main 类相同的 AppDomain 中运行。您正在实例化一个新的 AppDomain 并执行 AppDomain.Load 这一事实并不意味着您现在正在您创建的另一个 AppDomain 内运行代码。最终,您所做的只是从程序集中获取导出的类型,然后在其中一种类型上调用属性/方法。但是您没有在任何地方表示调用将发生在另一个 AppDomain 中。

有关进行跨 AppDomain 调用的一些信息,请参阅这些帖子:

Simplest way to make cross-appdomain call?

Cross AppDomain call is executed in caller Domain

【讨论】:

  • 感谢@Rajeev,尽管他们没有回答我的具体问题,但他们对理解我的问题很有帮助。
猜你喜欢
  • 1970-01-01
  • 2023-03-26
  • 2011-01-03
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多