Reputation: 1006
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
Reputation: 6821
Don't risk it, get it from the one who knows best: http://csharpindepth.com/articles/general/singleton.aspx
Upvotes: 0
Reputation: 369
There are several classic implementations of a singleton based on:
Upvotes: 0
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:
private static readonly <<YourClass>> singleton = new <<YourClass>>()
public <<YourClass>> Singleton
{
get { return singleton; }
}
Upvotes: 1