这也许是做你想做的事情的一种方法。我在这里演示的是将元数据传递和接收到创建的AppDomain
viaSetData
和GetData
方法,所以不管我如何创建实际的远程类型。
using System;
using System.Reflection;
namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
AppDomain appDomain = AppDomain.CreateDomain("foo");
appDomain.SetData(FooUtility.SourceKey, FooUtility.SourceValue);
IFoo foo = (IFoo)appDomain.CreateInstanceFromAndUnwrap(Assembly.GetEntryAssembly().Location, typeof(Foo).FullName);
foo.DoSomething();
}
}
public static class FooUtility
{
public const string SourceKey = "Source";
public const string SourceValue = "Foo Host";
}
public interface IFoo
{
void DoSomething();
}
public class Foo : MarshalByRefObject, IFoo
{
public void DoSomething()
{
string source = AppDomain.CurrentDomain.GetData(FooUtility.SourceKey) as string;
if (String.IsNullOrWhiteSpace(source))
source = "some default";
Console.WriteLine(source);
}
}
}
哪个输出:
Foo Host
按任意键继续...
因此,在您的情况下,您可以将任何源元数据传递给 AppDomain:
this._appDomain = AppDomain.CreateDomain(this._appName, AppDomain.CurrentDomain.Evidence, appDomainSetup);
this._appDomain.SetData("Source", "MyController");
this._startStopControllerToRun = (IStartStop)this._appDomain.CreateInstanceFromAndUnwrap(assemblyName, this._fullyQualifiedClassName);
this._startStopControllerToRun.Start();
并在您的GetSource
方法中检查它的存在。
private static string GetSource()
{
try
{
string source = AppDomain.CurrentDomain.GetData("Source") as string;
if (!String.IsNullOrWhiteSpace(source))
return source;
var assembly = Assembly.GetEntryAssembly();
// GetEntryAssembly() can return null when called in the context of a unit test project.
// That can also happen when called from an app hosted in IIS, or even a windows service.
if (assembly == null)
{
// From http://stackoverflow.com/a/14165787/279516:
assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
}
return assembly.GetName().Name;
}
catch
{
return "Unknown";
}
}
更新替代方案
您还可以声明一个公共接口方法,用于在目标域中的静态位置设置源。
using System;
using System.Reflection;
namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
AppDomain appDomain = AppDomain.CreateDomain("foo");
IFoo foo = (IFoo)appDomain.CreateInstanceFromAndUnwrap(Assembly.GetEntryAssembly().Location, typeof(Foo).FullName);
foo.SetSource("Foo Host");
foo.DoSomething();
}
}
public interface IFoo
{
void DoSomething();
void SetSource(string source);
}
public class Foo : MarshalByRefObject, IFoo
{
public void DoSomething()
{
string source = Foo.Source;
if (String.IsNullOrWhiteSpace(source))
source = "some default";
Console.WriteLine(source);
}
public static string Source{get; private set;}
public void SetSource(string source)
{
Foo.Source = source;
}
}
}