I’ve been playing around with MVC4 and I have created a data access layer which is currently a singleton.
My question is, is this a good idea? I’ve got a polling method in my layer which is the main reason I made it a singleton (this polling method checks the database and then uses signalr to update the UI)
I also thought it would be a good idea to use a singleton so I could cache data but I’m abit unsure now, how would this single cope with say 400 concurrent users?
any help would be great!
Code –
public class DataAccessLayer
{
private static DataAccessLayer _instance;
public static DataAccessLayer Instance
{
get
{
lock (_instance)
{
if (_instance == null)
_instance = new DataAccessLayer();
return _instance;
}
}
}
}
public class HomeController : Controller
{
public ActionResult GetUsers()
{
return View(DataAccessLayer.Instance.GetUsers());
}
}
You will have to deal threading issues with a singleton or a static class. Locking helps but it will makes things slower, especially since you do not check if the instance is already set before the lock.
Also, it would be difficult to unit test the code.
I would suggest setting an instance of the
DataAccessLayerin the controller using a constructor. An IoC container or a custom controller factory can be used to create the class instance and pass it to the controller.For easier unit testing/mocking, implement an
IDataAccessLayerinterface for the concrete class and use it as the parameter type in the controller constructor.