在我的 ASP.NET MVC 应用程序中,我有一个包含所有业务逻辑/服务层的项目。该项目与位于单独项目中的我的数据库(实体框架)交互。
我想轻松访问服务层,因此我在其中创建了静态类,以便可以轻松引用它们。例如,如果我在我的控制器中并且需要创建一个新帐户:
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 问题?