AppDomain DoCallBack FileNotFoundException - C#

2019-07-28 11:16发布

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.

标签: c# appdomain
2条回答
【Aperson】
2楼-- · 2019-07-28 11:46

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.

查看更多
Juvenile、少年°
3楼-- · 2019-07-28 11:48

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.

查看更多
登录 后发表回答