【问题标题】:How to access UserProfile in _Layout View如何在 _Layout 视图中访问 UserProfile
【发布时间】:2013-09-05 16:31:28
【问题描述】:

在我的 MVC 应用程序中,我有一个共享的 _Layout.cshtml 文件,用于显示用户的菜单

在该视图上,我想显示来自 UserProfile 实体的信息 - 使用 SimpleMembership 创建并因此链接到可以在 _Layout 页面中直接访问的 IPrincipal User。

所以我写了一个扩展方法来调用我的 UnitOfWork,看起来像这样:

    public static UserProfile GetUserProfile(this IPrincipal u)
    {
        IUnitOfWork uow = new UnitOfWork();
        return uow.UserRepository.GetUserProfile(u);            
    }

现在这可行,但它闻起来并不好,因为我正在实例化 UnitOfWork 而不是注入它....

我有一个如下所示的 BaseController 类:

public class BaseController : Controller
{
    // NOT NECESSARY TO DISPOSE THE UOW IN OUR CONTROLLERS
    // Recall that we let IoC inject the Uow into our controllers
    // We can depend upon on IoC to dispose the UoW for us
    protected MvcApplication.Data.Contracts.IUnitOfWork _Uow { get; set; }
}

(我的一些代码基于这个答案:https://stackoverflow.com/a/12820444/150342

我使用包管理器安装 StructureMap 并且此代码在应用程序启动时运行:

public static class StructuremapMvc
{
    public static void Start()
    {
        IContainer container = IoC.Initialize();
        DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);
    }
}

据我了解,这会将我的具体 UnitOfWork 类注入到我的控制器中,并处理 UnitOfWork 的处置。

不幸的是,就我对 IoC 的理解而言,如果我想从控制器以外的其他地方访问 UnitOfWork,或者我是否可以将信息传递给 _Layout,我不确定该怎么做我的控制器。我想将数据放到 _Layout 页面上,但我对如何从那里访问 UnitOfWork 或如何将 UnitOfWork 注入扩展方法感到困惑

【问题讨论】:

    标签: asp.net-mvc dependency-injection structuremap


    【解决方案1】:

    将数据放入 ViewBag 中,让 _Layout 视图从那里拉取数据。

    你可以把它放在你的BaseController

    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);
        var u = requestContext.HttpContext.User;
        var data = _UoW.UserRepository.GetUserProfile(u);
    
        ViewBag.UserData = data;
    }
    

    然后在布局视图中渲染数据:

    @ViewBag.UserData 
    

    【讨论】:

    猜你喜欢
    • 2011-10-28
    • 2020-12-22
    • 2014-10-20
    • 2021-02-05
    • 1970-01-01
    • 2018-08-30
    • 2017-04-27
    • 1970-01-01
    • 2016-03-02
    相关资源
    最近更新 更多