People who are using entity framework for Dal single dbcontext is going to be a problem in BLL. I use the following structure
I used to get the single dbContext by:- Each single repo class should inherit from base repo class and in base repo class should initialise the dbcontext.
The BaseRepository
public class BaseRepo
{
private readonly bool isNewInstance;
protected OnlineProductLinkEntitiesdbContext;
protected BaseRepository()
{
dbContext = newOnlineProductLinkEntities();
isNewInstance = true;
}
protectedBaseRepository(OnlineProductLinkEntitiesdbContext)
{
isNewInstance = dbContext == null;
if (isNewInstance)
dbContext = newOnlineProductLinkEntities();
this.dbContext = dbContext;
}
protected voidCheckAndTryToOpenConnection()
{
if (dbContext == null)
dbContext = newOnlineProductLinkEntities();
if (dbContext.Connection.State !=ConnectionState.Open)
dbContext.Connection.Open();
}
public void Dispose()
{
if ((!isNewInstance) || (dbContext ==null))
return;
OnlineProductLinkEntities context = (OnlineProductLinkEntities)dbContext;
if (context.Connection.State ==ConnectionState.Open)
{
context.Connection.Close();
}
context.Dispose();
dbContext=null;
}
}
The single repo class constructor looks like
public Cmo_SiteRepository(){}
public singleRepo (OnlineProductLinkEntitiesdbContext):base(dbContext), Irepository<model, entity>
{ }
A method inside the single repo class will look like this
public int Create(SiteModel model)
{
try
{
CheckAndTryToOpenConnection();
objectTable siteEntity = newobjectTable ();
}
catch (Exception ex)
{
throw new Exception("Exception", ex);
}
}
Comments
Post a Comment