在我的MVC應用程序我有一個顯示菜單爲用戶如何訪問用戶配置在_layout查看
該視圖我想要顯示從用戶配置實體的信息共享_Layout.cshtml文件 - 使用SimpleMembership和創建從而鏈接到可直接在_Layout頁面訪問的IPrincipal用戶。
所以我寫了一個擴展方法,使我的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的理解而言,我不知道如果要從Controller以外的某個位置訪問UnitOfWork,或者我是否可以將信息傳遞給_Layout從我的控制器。我想將數據放到_Layout頁面上,並且我很困惑如何從那裏訪問UnitOfWork,或者如何將UnitOfWork注入擴展方法
我沒有使用Html.Action渲染的局部視圖已經解決了這個(HTTP ://stackoverflow.com/a/5049950/150342),但這會讓我覺得這是一個更好的方法。 – Colin