如何创建应用程序域并在其中运行我的应用程序?
我需要创建一个自定义应用程序域来解决.NET运行时默认行为中的错误。 我在网上看到的示例代码都没有用,因为我不知道在哪里放置它,或者我需要在Main()
方法中替换它。
应该注意的是,创建AppDomain只是为了解决可以用常量字符串修复的东西可能是错误的方法。 如果您尝试执行与您提到的链接相同的操作,则可以执行以下操作:
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); } }
你需要:
1)创建AppDomainSetup对象的实例,并使用您想要的域设置信息填充它
2)使用AppDomain.CreateDoman方法创建新域。 具有配置参数的AppDomainSetup实例将传递给CreateDomain方法。
3)使用域对象上的CreateInstanceAndUnwrap方法在新域中创建对象的实例。 此方法获取您要创建的对象的typename,并返回一个远程代理,您可以在yuor主域中使用该远程代理与在新域中创建的对象进行通信
完成这3个步骤后,您可以通过代理调用其他域中的方法。 您也可以在完成后卸载域并重新加载。
MSDN帮助中的这个主题提供了您需要的非常详细的示例