简体   繁体   English

c#具有多个DLL的Singleton模式

[英]c# Singleton Pattern with multiple DLLs

My question is about a singleton pattern used in the following constellation of assemblies and libraries. 我的问题是关于在以下星座组件和库中使用的单例模式。

Imagine the following assemblies 想象一下以下的组件

  • CommonLibrary.dll CommonLibrary.dll
  • MainProcess.exe MainProcess.exe
  • Plugin1.dll Plugin1.dll
  • Plugin2.dll Plugin2.dll

MainProcess.exe, Plugin1.dll, and Plugin2.dll use the class Manager from CommonLibrary.dll. MainProcess.exe,Plugin1.dll和Plugin2.dll使用CommonLibrary.dll中的类Manager The CommonLibrary.dll is linked against the other assemblies at compile time. CommonLibrary.dll在编译时链接到其他程序集。 The Manager class uses the singleton pattern: Manager类使用单例模式:

public class Manager
{
    private static Manager instance;

    public static Manager Instance
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        get { 
            if (instance == null)
            {
                instance = new Manager();
            }
            return instance;
        }
    }

    private Manager()
    {

    }

    // methods ...
}

The singleton pattern is used to create only one instance of the Manager class (obviously). 单例模式用于仅创建Manager类的一个实例(显然)。 This is important in the methods of Manager because access to resources needs to be coordinated with different locks. 这在Manager的方法中很重要,因为对资源的访问需要与不同的锁协调。 Eg by using lock: 例如,使用锁:

// Method inside Manager
public void DoSomething()
{
    lock(someLockObject)
    {
         // do something
    }
}

MainProcess.exe, Plugin1.dll, and Plugin2.dll each have a reference to the Manager somewhere in their code by calling MainProcess.exe,Plugin1.dll和Plugin2.dll都通过调用在代码中的某个地方引用了Manager

Manager manager = Manager.Instance;
// do something with manager

Now imagine the following scenario: MainProcess.exe loads Plugin1.dll and Plugin2.dll using reflection during runtime using Assembly.LoadFrom(); 现在假设以下场景:MainProcess.exe使用Assembly.LoadFrom()在运行时使用反射加载Plugin1.dll和Plugin2.dll;

Question: Do MainProcess.exe, Plugin1.dll, and Plugin2.dll share the same instance of Manager? 问题:MainProcess.exe,Plugin1.dll和Plugin2.dll是否共享相同的Manager实例? This is important because if they do not share the same instance of Manager i need to do some inter process locking of resources. 这很重要,因为如果他们共享相同的Manager实例,我需要进行一些进程间的资源锁定。

Thanks. 谢谢。

Do MainProcess.exe, Plugin1.dll, and Plugin2.dll share the same instance of Manager? MainProcess.exe,Plugin1.dll和Plugin2.dll共享相同的Manager实例吗?

Yes, they do. 是的,他们这样做。 There will be only one instance of Manager in the application domain (and in the whole process, unless you explicitly create another AppDomain ). 应用程序域中只有一个Manager实例(在整个过程中,除非您明确创建另一个AppDomain )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM