Discussion Locked

.NET Global singleton class

0 helpful
5 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
Can I create a Singleton class in a global assembly that is shared among different processes? In other words, every process that has a reference to that library obtains always a reference to the same object when it instantiates such a class

5 replies

by gaston nusimovich

Yes, it is fairly easy to create a simple Singleton class in .NET.

You may check a sample code of such a class in my blog: http://spaces.msn.com/argenus/

There is an entry on April 21st (check archive of April 2006), "Deconstructing Design Patterns (DPs)", that contains a code sample (in C#) for a Singleton class.

This class implementation is not thread safe, I repeat, not thread safe.

To make it thread safe would require some redesign of the class, but that should not be very difficult of you are versant in free threading in .NET.

Good luck!

by eldergabriel

I'm not sure offhand. But you can try declaring a static class inside a namespace (to be used in common by client assemblies/applications). Then, try to crunch out an assembly with this namespace code, and see if your compiler chokes.

If your tools let you do this, then try running two separate processes that import this namespace and utilize the static resource contained therein. Maybe try setting a property in one process, and getting it from the other, and see what kind of results you get. I could be wrong, but this might work.

Of course, being static, that would probably eliminate the whole instantiation aspect of the scenario, but you'd have your shared class, i suppose.

I think that when you pass an object by reference, even between assemblies, by default the references are talking about the same object, anyway, so you may not need to even try the static class thing, now that i think about it.

by yaoliu68

I don't think you can do this. because each process has its own memory space, so we get each singleton instance per process. However, in win32, you can have 2 processes share the same memory space, but it will be a different story.

by spawn1969

Until .NET 4.0, this is not available. But you can use native Win32 memory mapped file to accomplish this. Simply creating a static class in an assembly does not achieve sharing this resource across applications.

Check out this link for Memory Mapped File usage.

http://msdn.microsoft.com/en-us/library/ms810613.aspx

However, if you want to explore implementing this in .NET, like I mentioned above, this is only available in .NET 4.0.

Link for sample:
http://blogs.msdn.com/salvapatuel/archive/2009/06/08/working-with-memory-mapped-files-in-net-4.aspx

This discussion is closed to new replies.