3

我正在使用基本的Unity MVC Nuget Bootstrapper。 我想在注入當前登錄的用戶進入服務我定義Unity MVC注入當前用戶

_container.RegisterType<IDoSomethingService, DoSomethingService>(); 

這樣DoSomethingService得到一個ICurrentUser物體或某種形式的解析器。

我試圖避免撥打電話一樣

DoSomethingService.DoSomething(currentUserUsingService,...); 

或者在所有的MVC控制器的構造還避免設置:

DoSomethingService.CurrentUSer = User.Identity.Name; 

回答

9

在我的項目中我用下一個:

public interface ICurrentUserService 
{ 
    int? GetId(); 
} 

我註冊下一個執行:

public class CurrentUserService: ICurrentUserService 
{ 
    public int? GetId() 
    { 
     if (!HttpContext.Current.User.Identity.IsAuthenticated) 
      return null; 
     return int.Parse(HttpContext.Current.User.Identity.Name);//When auth - id stored in cookie 
    } 
} 

_container.RegisterType<ICurrentUserService, CurrentUserService>(); 

並使我的服務取決於ICurrentUserService(通過使用ctor參數)或將userId傳遞到我在控制器中的服務的方法。