Reputation: 169
I want to have a single repository for all my classes/entities. All the controllers from an MVC app should be able to use this repository without creating new instances. The repository must have an extracted interface, for testing or other purposes - therefore the repository class will not be static, since static classes cannot implement interfaces. Yet, it will have a static property, which will be available without instantiating the Repository class. The constructor might be redundant or replaced by a method. Please let me know if it's a good implementation or a bad practice. Or let me know if could be improved somehow:
public class Repository : IRepository
{
private MyDBContext context;
private static Repository _instance;
public static Repository Instance
{
get
{
if(_instance == null)
{
_instance = new Repository(new MyDBContext());
}
return _instance;
}
}
public Repository(MyDBContext context)
{
this.context = context;
if(_instance == null)
{
_instance = new Repository(context);
}
}
...
}
Upvotes: 2
Views: 216
Reputation: 5480
There is nothing technically wrong with what you propose. There are some improvements though. The static constructor is guaranteed to run once and only once before the first call to a static member. You therefore remove the race condition you had in your code when 2 method call your Instance property. The null coalescing operator in the constructor means you get a default implementation, but you could override it for testing.
public class Repository : IRepository
{
private MyDBContext context;
public static IRepository Instance
{
get;
private set;
}
static Repository()
{
Instance = new Repository(null);
}
public Repository(MyDBContext context)
{
this.context = context ?? new MyDBContext();
}
}
Upvotes: 1