我需要创建一个自定义应用程序域来解决 .NET 运行时的 默认行为 中的一个错误。在线上看到的所有示例代码都不太有用,因为我不知道它应该放在哪里,或者需要替换我的 Main()
方法中的什么内容。
需要注意的是,仅仅为了解决可以通过常量字符串修复的问题而创建 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);
}
}
MarshalByRefObject
,否则它将只尝试将副本序列化回原始的AppDomain。 - Matthew Whited
AppDomain
对象上的.ExecuteAssembly(...)
方法,您可以提供包含入口点的另一个程序集的路径。 这可能会带来稍微更干净的设计,但至少需要两个程序集。 - Matthew Whitedmscoree.tlb
的情况下完成它。 - Matthew Whited