SubSonic 3 simple repository question
-
13-10-2019 - |
سؤال
I am using simple repository pattern of Subsonic 3 to store and get values from database. I want to know if I should use Singleton patten to create SimpleRepository
or should create one whenever is needed. Like if I have Person class like this:
public class Person
{
public void Save()
{
var repo=new SimpleRepository("constr"); //CREATE REPO HERE
repo.Add<Person>(this);
}
public void Load(int id)
{
var repo=new SimpleRepository("constr");//CREATE REPO HER
.....
}
}
Or access repo like this
public class Person
{
public void Save()
{
var repo=RepoHelper.GetRepository();//GET FROM SINGLETON OBJECT
repo.Add<Person>(this);
}
public void Load(int id)
{
var repo=RepoHelper.GetRepository();
.....
}
}
المحلول
I use a singleton class for it. It seems to be the right thing when you have a centralized data store. I allows you to manage the type of repository in one place. Is also has the advantage that it makes it easier to switch from reposition type.
public static class Repository
{
static SimpleRepository repo;
public static IRepository GetRepository()
{
if (repo == null)
{
lock (repo)
{
repo = new SimpleRepository("NamedConnectionString",
SimpleRepositoryOptions.RunMigrations);
}
}
return repo;
}
}
Ps. I also build a base record class to do a Save() and to manage foreign relations.
لا تنتمي إلى StackOverflow