在我的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问题?