在我的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()
一個非靜態類,需要在使用它的任何地方實例化,並且由於多個datacontext實例而不會遇到CRUD問題?
「事實上,一些最好的幫手方法是靜態的」你最好的概念是什麼? – 2010-11-09 02:58:02