Asp.net-Mvc

ASP.NET MVC:HTTPContext 和依賴注入

  • May 18, 2009

目前我有一個 ActionFilter 從 HttpContext 獲取目前使用者名並將其傳遞給在服務方法上使用它的操作。例如:

Service.DoSomething(userName);

我現在有理由不在操作級別而是在控制器建構子級別執行此操作。目前我正在使用結構映射來創建控制器並註入服務。我正在看類似的東西:

public interface IUserProvider
{
   string UserName { get; }
}

public class HttpContextUserProvider : IUserProvider
{
   private HttpContext context;

   public HttpContextUserProvider(HttpContext context)
   {
       this.context = context;
   }

   public string UserName
   {
       get
       {
           return context.User.Identity.Name;
       }
   }
}

也就是說,我的 IoC foo 真的很弱,因為這是我使用它的第一個項目。

所以我的問題是……我如何告訴結構映射在 HttpContextUserProvider 的建構子中傳遞 HttpContext?這看起來很奇怪……我不確定如何看待 HttpContext。

有一個介面抽象HttpContext.Current。隻公開你需要的方法。GetUserName()例如,將呼叫HttpContext.Current.User.Identity.Name實現。讓它盡可能薄。

採用該抽象並將其註入您的其他提供程序類。這將允許您通過模擬 http 上下文抽象來測試提供程序。作為附帶的好處,HttpContext除了模擬它之外,您還可以使用該抽像做其他漂亮的事情。重複使用它,一方面。將通用類型參數添加到包等。

聽起來您應該使用HttpContextBase而不是HttpContextUserProvider. 這是一個開箱即用的抽象,HttpContext允許您創建模擬、編寫單元測試並註入您的依賴項。

public class SomethingWithDependenciesOnContext
{
   public SomethingWithDependenciesOnContext(HttpContextBase context) {
       ...
   }

   public string UserName
   {
       get {return context.User.Identity.Name;}
   }
}

ObjectFactory.Initialize(x => 
         x.For<HttpContextBase>()
         .HybridHttpOrThreadLocalScoped()
         .Use(() => new HttpContextWrapper(HttpContext.Current));

引用自:https://stackoverflow.com/questions/877712