简体   繁体   English

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

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

I have a reference to a singleton (CacheLayer ) from a class (InnerModuleInfoLoader) loaded inside a child domain. 我有一个从子域中加载的类(InnerModuleInfoLoader)对单例(CacheLayer)的引用。 The problem is that this reference is not the same instance as for the rest of the code living in main domain. 问题在于,该引用与主域中其余代码的实例不同。 I wonder if exists any way to circumvent the execution isolation of appDomain to use the instance of the singleton? 我想知道是否存在任何方法可以避免appDomain的执行隔离以使用单例实例?

Here is the code: 这是代码:

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

Instantiating class from subdomain 从子域实例化类

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

Inside InnerModuleInfoLoader: Bellow I would like that CacheLayer.Instance will be the same for parent and subdomains. 在InnerModuleInfoLoader内部:在下面,我希望CacheLayer.Instance对于父域和子域都相同。

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

Singleton 辛格尔顿

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
}

Subdomain creation 子域创建

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? 我想知道是否存在任何方法可以避免appDomain的执行隔离以使用单例实例?

You can use MarshalByRefObject , that is, make your CacheLayer class inherit from it. 您可以使用MarshalByRefObject ,即使CacheLayer类继承自它。

Keep in mind, marshaling calls between AppDomains comes at a performance penalty. 请记住,AppDomain之间的封送调用会降低性能。 I would consider just having two difference caches for each AppDomain. 我会考虑每个AppDomain仅具有两个不同的缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM