Below the slides that I used for my session during the MS Days in Grenoble. The session and slides were done in French.
Wednesday, June 8, 2011
Wednesday, June 1, 2011
You can find an article of 5 pages concerning Entity Framework 4.1 and CodeFirst in the French Programmez magazine No.142 written by me and Fathi Bellahcene.
The article is written in French but as always I will write some English articles on my Blog in the next weeks. So stay tuned if you are interested in getting to know the new features of Entity Framework 4.1 and the CodeFirst approach.
You can find the source code here:
Class with only one single possible instance
Often used for objects that need to provide global access with the constraint of only one single instance in the application
1 / 5
UML Class Diagram:
- There are multiple ways of implementing the Singleton Pattern in C#. I am going to explain the most efficient approaches that also provide thread safety.
- Note that in the first example the default constructor is defined as private so that it is not possible to instantiate the object from the outside. The class is also marked as sealed which means that inheritance is not allowed for it.
- The internally instantiated object is stored in a private variable that is marked as static. The public static property GetInstance is used to allow access to this object. It contains the business logic that assures that only a single instance can ever exist.
- To achieve this behavior a lock strategy is used to assure that only a single thread is allowed to do the null check and create a new instance if it does not already exist.
- A test function DisplayConfiguration() was added to be able to verify the class design.
- Note that in the second example the default constructor is also defined as private so that it is not possible to instantiate the object from the outside. The class is also marked as sealed which means that inheritance is not allowed for it.
- This time a private nested class is used to provide access to the instance that must only exist once in the application.
- This nested class has a static default constructor and an internal static read-only instance of the object. Only the container class has access to the instance which will due to the software design (auto-instantiated and marked as read-only) only exist once.
- A test function DisplayRules() was added to be able to verify the class design.
- I recommend using this example as your default approach for your Singleton implementations since there is no locking in it which makes it more efficient in terms of performance.
- In the last step we add some code to test the software design and the Singleton implementation.
- When running the example you can see that everything is working as expected (it is however not as simple to test that there really is just one single instance, you just have to believe in the correct software design).