The Repository class has singleton behavior and the _db implements the disposable pattern. As excepted the _db object gets disposed after the first call and because of the singleton behavior any other call of _db will crash.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class Repository : IRepository
{
private readonly DataBase _db;
public Repository(DataBase db)
{
_db = db;
}
public int GetCount()
{
using(_db)
{
return _db.Menus.Count();
}
}
public Item GetItem(int id)
{
using(_db)
{
return _db.Menus.FirstOrDefault(x=>x.Id == id);
}
}
}
My question is, is there any way to design this class to work properly without removing the singleton behavior? The Repositoryclass will be serving big amount of requests.
When you supply a
DataBaseinstance to theRepository, this means creation and disposal is not in the scope of theRepositoryclass. Therefore,Repositoryshould not dispose that instance. You should remove theusingstatements, and you’ll be fine. Write theRepositoryas follows: