Amin Uddin
Amin Uddin

Reputation: 1006

How to create a singleton pattern of the following class

I have a class to create object context. To manage object creation, I want to use singleton pattern. How to create following class object creation pattern as singleton in C# ?

  public abstract class EFContextBase<TContext> : IDisposable where TContext : ObjectContext, new()
        {
            private TContext _dataContext;
                protected virtual TContext DataContext
            {
                get
                {
                    if ((object)this._dataContext == null)
                        this._dataContext = Activator.CreateInstance<TContext>();
                    return this._dataContext;
                }
            }

  public EFContextBase()
            {
                this.DataContext.ContextOptions.LazyLoadingEnabled = true;
            }
                public void Dispose()
            {
                this.Dispose(true);
                GC.SuppressFinalize((object)this);
            }
                private void Dispose(bool disposing)
            {
                if (!disposing || (object)this._dataContext == null)
                    return;
                this._dataContext.Dispose();
                this._dataContext = default(TContext);
            }
        }

Upvotes: 0

Views: 475

Answers (3)

David Osborne
David Osborne

Reputation: 6821

Don't risk it, get it from the one who knows best: http://csharpindepth.com/articles/general/singleton.aspx

Upvotes: 0

Roman Ambinder
Roman Ambinder

Reputation: 369

There are several classic implementations of a singleton based on:

  1. Static constructor initialization (Thread safe by design)
  2. Instance property getter double locking for thread safety returning value.
  3. .Net Lazy wrapper based property(can be configured to be thread safe, in constructor).

Upvotes: 0

BendEg
BendEg

Reputation: 21128

Why making an abstract class Singleton? Abstract classes were made, to be inherited by other classes. Singleton is an design pattern for avoiding static methods and keep the possibility, to make your class instanceable (Maybe for later use). You should think about your architecture.

In general you should make a class singleton in the following way:

  1. Define a private constructor
  2. Define a private variable: private static readonly <<YourClass>> singleton = new <<YourClass>>()
  3. Define a public singleton property:
public <<YourClass>> Singleton
{
    get { return singleton; }
}

Upvotes: 1

Related Questions