Jump to content

Signleton Design Pattern For Database Class


pr.nimbalkar
 Share

Recommended Posts

Not necessarily, for example, you could have an instance for each table you were operating on, or an instance per database.

Link to comment
Share on other sites

I don't think it really makes a difference as long as you are closing your connections after you are done using them. I don't use a true Singleton with my Repository class but it seems like a similar idea. I use a static data context and use static methods for retrieving data. (This is designed for LINQ to SQL)

public class Repository<T> : IDisposable where T : class, IEntity {	 private static DataContext _context = null;	 private TransactionScope _scope = null;	 	 public Repository() {	 	 }	 	 public static DataContext Context {		 get {			 if(_context == null)				 _context = DataHelper.GetDataContext();			 			 return _context;		 }		 set { _context = value; }	 }	 	 public static T Get(int id) {		 var entity = Context.GetTable<T>()			 .Where(x => x.Id == id);			 		 return entity.Count() == 1 ?			 entity.Single() : default(T);	 }	 	 public static ICollection<T> Find(Func<T, bool> expression) {		 		 var list = Context.GetTable<T>()			 .Where(expression);			 		 return list.Count() > 0 ?			 list.ToList() : new List<T>();	 }	 	 public void Save(T entity) {		 if (_scope == null)			 throw new ApplicationException("Cannot save entity. Scope is null.");	 		 if(entity.Id == 0)			 Context.GetTable<T>().InsertOnSubmit(entity);	 }	 	 public void Delete(T entity) {		 if (_scope == null)			 throw new ApplicationException("Cannot delete entity. Scope is null.");			 		 if(entity.Id > 0)			 Context.GetTable<T>().DeleteOnSubmit(entity);	 }	 	 public void BeginTransaction() {		 _scope = new TransactionScope();	 }	 	 public void CommitTransaction() {		 if(_scope == null)			 throw new ApplicationException("Cannot commit transaction. Scope is null.");		 		 Context.SubmitChanges();		 _scope.Complete();	 } 	 public void Dispose() {		 if(_scope != null) _scope.Dispose();	 } }

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...