2013-09-05 15 views
1

在我的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注入擴展方法

回答

2

將數據放入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 
+0

我沒有使用Html.Action渲染的局部視圖已經解決了這個(HTTP ://stackoverflow.com/a/5049950/150342),但這會讓我覺得這是一個更好的方法。 – Colin

相關問題