代码之家  ›  专栏  ›  技术社区  ›  Dan Is Fiddling By Firelight Leniency

如何创建应用程序域并在其中运行应用程序?

  •  21
  • Dan Is Fiddling By Firelight Leniency  · 技术社区  · 15 年前

    我需要创建一个自定义应用程序域来解决.NET运行时中的错误。 default behavior . 我在网上看到的示例代码中没有一个是有用的,因为我不知道将它放在哪里,或者需要在我的 Main() 方法。

    2 回复  |  直到 15 年前
        1
  •  38
  •   Matthew Whited    8 年前

    应该注意的是 AppDomains 只是绕过一些可以用常量字符串修复的问题,这可能是错误的方法。如果您尝试执行与您注意到的链接相同的操作,则可以执行以下操作:

    var configFile = Assembly.GetExecutingAssembly().Location + ".config";
    if (!File.Exists(configFile))
        throw new Exception("do your worst!");
    

    递归入口点 o)

    static void Main(string[] args)
    {
        if (AppDomain.CurrentDomain.IsDefaultAppDomain())
        {
            Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
    
            var currentAssembly = Assembly.GetExecutingAssembly();
            var otherDomain = AppDomain.CreateDomain("other domain");
            var ret = otherDomain.ExecuteAssemblyByName(currentAssembly.FullName, args);
    
            Environment.ExitCode = ret;
            return;
        }
    
        Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
        Console.WriteLine("Hello");
    }
    

    使用非静态辅助入口点和MarshalByRefObject快速采样…

    class Program
    {
        static AppDomain otherDomain;
    
        static void Main(string[] args)
        {
            otherDomain = AppDomain.CreateDomain("other domain");
    
            var otherType = typeof(OtherProgram);
            var obj = otherDomain.CreateInstanceAndUnwrap(
                                     otherType.Assembly.FullName,
                                     otherType.FullName) as OtherProgram;
    
            args = new[] { "hello", "world" };
            Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
            obj.Main(args);
        }
    }
    
    public class OtherProgram : MarshalByRefObject
    {
        public void Main(string[] args)
        {
            Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
            foreach (var item in args)
                Console.WriteLine(item);
        }
    }
    
        2
  •  6
  •   mfeingold    15 年前

    你需要:

    1)创建AppDomainSetup对象的实例,并用您所需的域设置信息填充它。

    2)使用appdomain.createdoman方法创建新域。带有配置参数的AppDomainSetup实例被传递到CreateDomain方法。

    3)使用域对象上的CreateInstanceAndUnwrap方法在新域中创建对象的实例。此方法接受要创建的对象的typename,并返回一个远程代理,您可以在yuor主域中使用该代理与在新域中创建的对象通信。

    完成这3个步骤后,可以通过代理调用另一个域中的方法。您也可以在完成后卸载域,然后重新加载。

    这个 topic 在msdn帮助中有一个非常详细的例子,说明您需要什么