嗨,我是存储库模式的新手。我想就我所遵循的方法获得反馈。
要求:为当前登录的用户构建菜单。
我的解决方案:
我创建了一个服务,控制器将调用它来获取菜单项。
public interface IApplicationHelperService { List<Menu> GetMenuForRoles(); }
服务的实现
public class ApplicationHelperService : IApplicationHelperService { private readonly IMenuRepository _menuRepository; //this fecthes the entire menu from the datastore private readonly ICommonService _commonService; //this is a Service that contained common items eg. UserDetails, ApplicationName etc. public ApplicationHelperService(IMenuRepository menuRepository,ICommonService commonService) { this._menuRepository = menuRepository; this._commonService = commonService; } public List<Menu> ApplicationMenu { get { return _menuRepository.GetMenu(_commonService.ApplicationName); } } List<Menu> IApplicationHelperService.GetMenuForRoles() { return ApplicationMenu.Where(p => p.ParentID == null && p.IsInRole(_commonService.CurrentUser.Roles)).OrderBy(p => p.MenuOrder).ToList(); } }
然后是 CommonService(用于服务中所需的常见项目,例如 CurrentUser
public interface ICommonService { IUser CurrentUser { get; } string ApplicationName { get; } }
在实现 ICommonService 的类上,我使用上下文获取当前用户,换句话说,我的服务层不知道 HttpContext,因为将来有可能将其用于另一种类型的应用程序。因此,通过这种方式,当前用户可以对所有应用程序进行不同的处理,但我的服务层不会介意。
所以你应该给出反馈的是,这种将这种公共服务注入所有服务的方法是一种好方法还是有另一种方法这样做,我问的原因是在稍后阶段我将需要当前用户的用于审计目的的详细信息或出现的任何原因。
希望这对某人有意义。:-)