gpt4 book ai didi

c# - 常见项目的存储库模式

转载 作者:太空狗 更新时间:2023-10-29 23:47:17 25 4
gpt4 key购买 nike

您好,我是存储库模式的新手。我希望就我所遵循的方法获得反馈。

要求:为当前登录的用户构建菜单。

我的解决方案:

  1. 我创建了一个服务, Controller 将调用该服务来获取菜单项。

    public interface IApplicationHelperService
    {
    List<Menu> GetMenuForRoles();
    }
  2. 服务的实现

    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();
    }

    }
  3. 然后是 CommonService(用于服务中所需的公共(public)项目,例如 CurrentUser

    public interface ICommonService
    {
    IUser CurrentUser { get; }
    string ApplicationName { get; }
    }

在实现 ICommonService 的类上,我让当前用户使用上下文,换句话说,我的服务层不知道 HttpContext,因为这有可能被用于另一种类型的应用程序 future 。因此,通过这种方式,我可以针对所有应用程序以不同方式处理当前用户,但我的服务层不会介意。

所以你应该提供反馈的是,这种将这种公共(public)服务注入(inject)所有服务的方法是一种好方法还是有另一种方法来做到这一点,我问的原因是在稍后阶段我需要当前用户的详细信息,用于审计目的或出现的任何原因。

希望这对某人有意义。 :-)

最佳答案

我们正在使用类似的方法。不同之处在于,我们没有将 CommonService 对象注入(inject)到每个服务中。

我们正在使用 WCF,我们已经编写了 OperationContext 的扩展来存储用户名等。可以使用静态方法调用来访问此扩展中定义的属性。它比 CommonService 实现有优势;由于您使用的是 IOC,因此没有直接的方法可以在每个服务调用中将参数传递给 CommonService。例如,如果您在 WCF 调用中发送用户名,则需要在每个构造函数中设置 CurrentUser 的值。

不知您是否打算使用WCF;但要点是:如果您需要将变量传递给您的 CommonService,您最终将在每个构造函数中填充此值。如果您不打算传递变量,那么您可以只为您的服务创建一个基类,并强制开发人员使用这个基类。

此外,您应该将 CommonService 的生命周期管理器设置为 UnityPerResolveLifeTimeManager,以免在每个构造函数中创建一个新实例。否则,您最终可能会在每个服务中拥有不同的实例。

关于c# - 常见项目的存储库模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11848476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com