简体   繁体   中英

Singleton objects across application in c#.net

I know that what is singleton pattern and how to create it and how to make it thread safe using locking and double checking but all I want to know " let's consider a scenario I have a .dll which does a have class that is singleton. Now there are two application which are using the .dll and accessing the singleton class object." So, singleton pattern provide single object application wide or it works across applications. in case, it doesn't work across application, then how to create a application wide singleton object without using any WCF or Web Service. Basically I want that a class object should be accessed across application should be same, using MarshalByRef or something .

You cannot, using language features alone, create an object instance that is a singleton across app domains, never mind processes. So, no…what you're asking to do is not literally possible

It seems you have specifically excluded various remoting APIs too, so you'll have to implement this at a lower level of abstraction. Ie explicitly managed inter-process communications, such as named pipes or sockets.

I would try very hard to avoid even having this requirement. But assuming you have some single machine-wide resource that truly needs to be treated as a singleton, IMHO the best way to approach it would be to create a service that is always running, and which serves up whatever resource is supposed to be shared by all of the running instances of your program.

Finally note that you can easily ensure only one instance of your program (for a given user login session or machine-wide, depending on implementation). The usual way of doing this is to use a named mutex, which your program will create/check on initialization, and if some other instance of the program has already created it, the new instance will exit. See How to restrict a program to a single instance for more details on that.

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