我希望轻松访问服务层,因此我在其中创建了静态类,以便可以轻松引用它们。例如,如果我在控制器中需要创建新账户:
ServiceLayer.Accounts.CreateAccount(userName, passWord) //etc..
服务层然后执行所有必要的逻辑,然后通过DatabaseLayer
中的存储库创建用户。
private static AllRepos _Repos;
private static AllRepos Repos {
get
{
if(_Repos == null)
_Repos = new AllRepos();
return _Repos
}
}
public static void CreateAccount(string username, password)
{
string salt = GenerateSalt();
Account newAccount = DatabaseLayer.Models.Account
{
Name = username,
Password = HashPassword(password, salt),
Salt = salt
};
Repos.AddAccount(newAccount);
}
因为我不想在我的服务层中到处执行以下操作:
AccountRepository Accounts = new DatabaseLayer.AccountRepository();
我相反地创建了一个仓库的包装类,这样我只需要实例化一次就可以使用所有其他仓库。
public class AllRepos
{
private AccountRepository _Accounts;
public AccountRepository Accounts
{
get
{
if (_Accounts== null)
_Accounts= new AccountRepository();
return _Accounts;
}
}
// the same is done for every other repository (currently have about 10+)
}
这是在服务层的静态类中使用的。
由于我的所有服务层类都是静态的,而Repos
字段也是静态的,明显的问题是同一个对象从多个数据上下文中检索出来,导致更新/删除时出现奇怪的行为。
我知道如果像我一样使用静态成员/类,这是可以预料到的,因为它们持续了应用程序的生命周期,但是否有一种方法可以在不创建需要实例化的非静态类的情况下,使用服务层作为ServiceLayer.Accounts.Method()
并且不会因为多个数据上下文实例而遇到CRUD问题?