C# 公共项的存储库模式
您好,我是存储库模式的新手。我想就我所遵循的方法获得反馈 要求:为当前登录的用户生成菜单 我的解决方案:C# 公共项的存储库模式,c#,unit-testing,repository,C#,Unit Testing,Repository,您好,我是存储库模式的新手。我想就我所遵循的方法获得反馈 要求:为当前登录的用户生成菜单 我的解决方案: 我创建了一个服务,控制器将调用该服务来获取菜单项 public interface IApplicationHelperService { List<Menu> GetMenuForRoles(); } 在实现ICommonService的类上,我使用上下文获取当前用户,换句话说,我的服务层不知道HttpContext,因为这可能在将来被用于另一种类型的应用程序。因此
public interface IApplicationHelperService
{
List<Menu> GetMenuForRoles();
}
希望这对某人有意义。:-) 我们正在使用类似的方法。不同之处在于,我们没有将CommonService对象注入到每个服务中 我们正在使用WCF,并且我们已经为OperationContext编写了一个扩展来存储用户名等。可以使用静态方法调用访问此扩展中定义的属性。它比CommonService实现具有优势;因为您使用的是IOC,所以在每个服务调用中并没有直接的方法将参数传递到CommonService。例如,如果要在WCF调用中发送用户名,则需要在每个构造函数中设置CurrentUser的值 我不知道您是否计划使用WCF;但关键是:如果需要将变量传递给CommonService,那么最终将在每个构造函数中填充这些值。如果您不打算传递变量,那么您可以为您的服务创建一个基类,并强制开发人员使用这个基类
此外,您应该将CommonService的生存期管理器设置为UnityPerResolveLifeTimeManager,以便不在每个构造函数中创建新实例。否则,您可能会在每个服务中都有不同的实例。我怀疑我们是否会使用WCF服务。关于参数传递,我怀疑是否有必要这样做。这更像是一种“静态类”方法。不过我会研究基类……我忘了在回答中提到,但是如果您需要解析一个服务类中的多个存储库;您可能还需要采用UnitOfWork模式,以便在事务中保存所有存储库中的更改。
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();
}
}
public interface ICommonService
{
IUser CurrentUser { get; }
string ApplicationName { get; }
}