简体   繁体   中英

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. 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?

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.

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?

You can use MarshalByRefObject , that is, make your CacheLayer class inherit from it.

Keep in mind, marshaling calls between AppDomains comes at a performance penalty. I would consider just having two difference caches for each AppDomain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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