如何在子应用程序域中使用来自主应用程序域的相同单例实例

How to use the same singleton instance from main appdomain in childs appdomain

我从子域中加载的 class (InnerModuleInfoLoader) 引用了单例 (CacheLayer)。 问题在于此引用与主域中其余代码的实例不同。 请问有没有办法绕过appDomain的执行隔离,使用单例实例?

代码如下:

AppDomain subdomain = this.CreatedChildDomain(AppDomain.CurrentDomain);

从子域

实例化class
var loader = (InnerModuleInfoLoader) subdomain.
    CreateInstanceFrom(loaderType.Assembly.Location, loaderType.FullName).Unwrap();

InnerModuleInfoLoader: Bellow 我希望 CacheLayer.Instance 对于父域和子域是相同的。

var server = CacheLayer.Instance.Get<string>("Server");

单例

public sealed class CacheLayer
{
    private static readonly CacheLayer instance = new CacheLayer();
    private static readonly ObjectCache cache;
    static CacheLayer()
    {
        cache = MemoryCache.Default;
    }
    private CacheLayer(){}
    //More code omitted
}

创建子域

protected virtual AppDomain CreatedChildDomain(AppDomain parentDomain)
{
    Evidence evidence = new Evidence(parentDomain.Evidence);
    AppDomainSetup setup = parentDomain.SetupInformation;
    return AppDomain.CreateDomain("ModuleFinder", evidence, setup);
}   

I wonder if exists any way to circumvent the execution isolation of appDomain to use the instance of the singleton?

你可以使用MarshalByRefObject,即让你的CacheLayerclass继承它

请记住,在 AppDomain 之间编组调用会降低性能。我会考虑为每个 AppDomain 使用两个不同的缓存。