不同 .NET 应用程序域中的实例使用相同的引用实例
我正在不同的应用程序域中创建两个实例(通过工厂),但它们最终使用相同的引用实例而不是每个实例。引用的实例依赖于非托管 dll,这可能是原因吗?
如何验证两个实例实际上在不同的应用程序域中运行?
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 引用了一个单例类,该类依赖于非托管 dll 中的代码。 myInstance1 和 myInstance2 引用相同的单例实例,即使它们在不同的应用程序域中执行。
这是怎么回事?我如何验证它们实际上是单独的应用程序域?
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 though they execute in separate app domains.
How can this be and how can I verify that they actually are separate app domains?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信您创建 AppDomain 的方式是可以的。但是,您并不是通过简单地调用工厂来将代码重定向到那里运行。您需要利用
MarshalByRefObject
。此 MSDN 页面有一个很好的示例,AppDomain.ExecuteAssembly 方法。这是重要的部分: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 leverageMarshalByRefObject
. This MSDN page has a good example, AppDomain.ExecuteAssembly Method. Here's the important part: