[英]ASP.NET MVC dependency injection and helpers
在asp.net MVC中,使用控制器進行依賴注入非常簡單明了。 現在,我想通過使用助手從視圖中刪除大多數邏輯。 問題在於這些助手使用了一些注入的對象。
讓我寫一個例子:
public interface ISessionData
{
List<string> IdList {get;}
}
public MyController : Controller
{
public MyController(ISessionData sessionData)
{
...
}
}
會話數據被注入控制器。 到現在為止還挺好。 但是現在我有了一個助手。 假設它看起來像這樣:
public class MyHelper
{
private readonly ISessionData sessionData;
public MyHelper(ISessionData sessionData)
{
this.sessionData = sessionData;
}
public bool CheckSomethingExistsInSession(string id)
{
return sessionData.IdList.Any(x => x.Id.Equals(id));
}
}
怎么辦? 我希望將MyHelper
插入視圖。 我唯一能看到的方法就是將這個助手添加到模型中,然后每次傳遞給視圖。 還有其他想法嗎?
在MVC中,最好將ISessionData數據從Controller傳遞到View(使用ViewModel或ViewData):
ViewData["Session"] = sessionData.IdList.ToList();
並從助手中刪除ISessionData依賴項。 像這樣:
public class MyHelper
{
//private readonly ISessionData sessionData;
public MyHelper(/*ISessionData sessionData*/)
{
//this.sessionData = sessionData;
}
public bool CheckSomethingExistsInSession(string id, IList<...> sessionData)
{
return sessionData.Any(x => x.Id.Equals(id));
}
}
在視圖中:
<% var somethingExists = new MyHelper().CheckSomethingExistsInSession(
1, ViewData["Session"] as IList<...>); %>
更新:
public static class MyHelper
{
public static bool CheckSomethingExistsInSession(string id, IList<...> sessionData)
{
return sessionData.Any(x => x.Id.Equals(id));
}
}
<% var somethingExists = MyHelper.CheckSomethingExistsInSession(
1, ViewData["Session"] as IList<...>); %>
您應該從控制器的構造函數中刪除會話邏輯,然后使用IModelBinder將其插入到控制器的操作方法中。 見下文:
public class SessionDataModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// Get/create session data implementating ISeesionData or whatever here. This will be return to the controller action method.
return new SessionData()
}
}
在控制器上,您將執行以下操作:
public MyController : Controller
{
public MyController()
{
....
}
public ActionResult Index(ISessionData sessionData)
{
// do stuff with ISessionData.
// Redirect or whatever.
return this.RedirectToAction("Index");
}
}
您需要像下面一樣添加IModelBinder才能調用它。 您可以在http應用程序的啟動中執行此操作。
System.Web.Mvc.ModelBinders.Binders[typeof(ISessionData)] = new SessionDataModelBinder();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.