Instances in separate .NET app domains use same referenced instance
I'm creating two instances (through a factory) in separate app domains but they end up using the same referenced instance instead of one each. The referenced instance is dependent on unmanaged dll's, could this be the reason?
How do I verify that two instances are actually running in separate app domains?
AppDomain appDomain1 = AppDomain.CreateDomain("AD1");
Factory factory1 = (Factory)appDomain1.CreateInstanceAndUnwrap(typeof(Factory).Assembly.FullName, typeof(Factory).FullName);
MyClass myInstance1 = factory1.CreateInstance();
AppDomain appDomain2 = AppDomain.CreateDomain("AD2");
Factory factory2 = (Factory)appDomain2.CreateInstanceAndUnwrap(typeof(Factory).Assembly.FullName, typeof(Factory).FullName);
MyClass myInstance2 = factory2.CreateInstance();
MyClass has a reference to a singleton class which has dependencies to code in unmanaged dll's. myInstance1 and myInstance2 refers to the same singleton instance even t开发者_Python百科hough they execute in separate app domains.
How can this be and how can I verify that they actually are separate app domains?
I believe the way you're creating the AppDomain
's is OK. But you are not redirecting your code to run there by simply calling your factory. You need to leverage MarshalByRefObject
. This MSDN page has a good example, AppDomain.ExecuteAssembly Method. Here's the important part:
// Create an instance of MarshalbyRefType in the second AppDomain.
// A proxy to the object is returned.
var mbrt = (MyTypeWhichIsAMarshalByRef)
ad2.CreateInstanceAndUnwrap(
exeAssembly,
typeof(MyTypeWhichIsAMarshalByRef).FullName);
// Call a method on the object via the proxy, passing the time
mbrt.SomeMethod(DateTime.Now);
// Unload the second AppDomain. This deletes its object and
// invalidates the proxy object.
AppDomain.Unload(ad2);
精彩评论