Unable to load executing assembly into new AppDoma

2019-06-04 13:56发布

问题:

I am trying to host a text template class proxy inside a new AppDomain.

I have some old scripting code that does something similar, that contains this working code:

_ScriptAppDomain = AppDomain.CreateDomain(scriptDomainFriendlyName);
_ScriptProxy = (IScriptEngineProxy)_ScriptAppDomain.CreateInstanceAndUnwrap(
    Assembly.GetExecutingAssembly().FullName,
    "LVK.Scripting.ScriptEngineProxy");

However, when I try this with my new class, with the following

_TemplateDomain = AppDomain.CreateDomain(templateDomainFriendlyName);
_TemplateProxy = (ITemplateProxy)_TemplateDomain.CreateInstanceAndUnwrap(
    Assembly.GetExecutingAssembly().FullName,
    "TextTemplate.TemplateProxy");

I just get "FileNotFoundException", with the following details:

Could not load file or assembly 'TextTemplate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bb70a2e62a722ace' or one of its dependencies. The system cannot find the file specified.

What am I missing?

Basically, I have a Template class in the TextTemplate namespace (and assembly), which tries to load a TemplateProxy class (descending from MarshalByRefObject) into the new appdomain, but it appears my main assembly is not loaded into this domain.

This works if I use the older code, but not with this new one, but I can't spot the difference.

Here's some more details:

  • Assembly is not registered with the GAC (neither was the old one, which works)
  • I have not overridden any AssemblyResolve event (neither did the old one, which works)

I'm not averse to handling the AssemblyResolve event, if that is what is needed. I just found it odd that my old code worked, and this didn't.

回答1:

Assumying your assembly is in the same directory as your current application base, try specifying Application Base:

        AppDomain.CreateDomain(templateDomainFriendlyName, null,
            new AppDomainSetup
            {
                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
            });


回答2:

If you don't know what you are doing, the best way to create a new domain is to copy all settings from the current one, like this:

        var newDomain = AppDomain.CreateDomain("NAME", 
                        AppDomain.CurrentDomain.Evidence,
                        AppDomain.CurrentDomain.SetupInformation);

I had similar issues, and making a copy resolved them for me



标签: c# appdomain