There are quite a few goodArticleI have introduced this topic, so I will not go into details about how to implement it. It is all in the reference materials below.
The disadvantage I want to talk about is that the static constructor may encounter exceptions.An exception is thrown by a static constructor, which not only causes access failure, but also prevents the constructor from being called again at runtime according to the characteristics that the static constructor only runs once,AndProgramDuring the lifetime of the application domain, the type remains uninitialized, leading to access failure. That is to say, after the first failed operation, there is no chance to fix the error.
For example, if you want to put some public data in the database, such as menus, or some permissions, In a Singleton, alternatively, you can cache the data of a single instance to memcached or appfabric for later use. If the database is unavailable or the cache service is unavailable, if the data retrieval or cache action fails, the static constructor encounters an exception, and the system cannot be accessed. If it is a web system, you must restart the application pool or WWW Service to solve the problem.
Therefore, I think static initialization may not be suitable for reading databases, storing caches, and other scenarios. These scenarios are highly probable, such as databases and websites on different machines, if the database and website server are restarted at the same time, the website server starts fast, and the database server starts slowly, the database is unavailable when the website provides services. In this way, once someone accesses the website, static constructor initialization starts. If an exception occurs, it cannot be repaired. No matter who accesses the database or whether the database is available, the system will directly return an error to you.
Therefore, in this case, the traditional Singleton implementation mode of lock is more reliable, and there is at least one chance to fix the error after the failure.
What do you think?
References:
Static Constructor (C # programming guide)
Http://msdn.microsoft.com/zh-cn/library/k9x6w0hc (V = vs.100). aspx
Singleton
Http://msdn.microsoft.com/zh-cn/library/ms998426.aspx
Implement Singleton in C #
Http://msdn.microsoft.com/zh-cn/library/ms998558.aspx
Static constructors and Way Forward (. NET optimized Singleton pattern)
Http://www.codeproject.com/KB/architecture/StaticCtor_Singleton.aspx