简体   繁体   中英

AppDomain DoCallBack FileNotFoundException - C#

I have a C# 2.0 class with the following code:

public class MyClass : MarshalByRefObject, IDisposable 
    {
        private string _appName;
        private AppDomain _app;

        public MyClass(string appName)
        {
            _appName = appName;
            _app = AppDomain.CreateDomain("NewDomain" + _appName);
            _app.DoCallBack(new CrossAppDomainDelegate(CallBackMethod));
        }

        public void Dispose()
        {
            AppDomain.Unload(_app);
        }

        public static void CallBackMethod()
        {
            //some operations
        }
    }

This class is contained under a Class Library Project, then referenced from a Web Application Project.

So, in my web page I just instance the object, expecting that the constructor of the class would create that new AppDomain and perform the specified operations:

MyClass objMyClass = new MyClass("12022012213456");

But I keep getting this error:

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

But the curious thing here is that this exception is happening at this line:

_app.DoCallBack(new CrossAppDomainDelegate(CallBackMethod));

And as you can see, it's happening on MyClass , so I don't understand how could it tell me that the assembly could not be found if the code is already being executed??? I just don't get it.

BTW, I'm a newbie at the usage of AppDomain, maybe I'm confused with some concept.

It appears that the AppDomain you created (_app) is having problems locating your MyClass class in it's assembly. Your CreateDomain has not provided any AppDomainSetup information so it has no context for the current app domains directories nor assemblies. You have two options, provide a propertly configured AppDomainSetup or call _app.Load(Assembly.GetExecutingAssembly.FullName) prior to your DoCallBack method.

I had this problem but the solution was different. In my situation, I needed to explicitly provide my own AppDomainSetup object and specify the ApplicationBase folder, so that it could actually find my assembly.

My code was loaded by another app, and that's why my assembly wasn't able to be found using the default settings.

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