在我的 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 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 注入扩展方法感到困惑