假设我有一个类似于每个试图访问我的网站的用户的对象。一种会话范围对象,它应该在我的整个"应用程序"中的每个视图/模型/控制器上可见。
当我调用一个页面并通过来自我自己的数据库的数据填充它时,我想创建它。
在视图上调用myObject.Title。在WebForms我这样做扩展类的UserControl,如:
public class iUserControl : System.Web.UI.UserControl
{
protected MyCurrentPage myCurrentPage;
public iUserControl()
{
}
protected override void OnLoad(EventArgs e)
{
myCurrentPage = new MyCurrentPageWrapper();
}
}
than,对于每个UserControl,像这样:
public partial class context_pippo_MyOwnUserControl : iUserControl
在MVC上,我看不到每个控件的任何扩展,所以我怎么能实现这种过程?我想摆脱存储元素的会话。
如果我理解正确的话,我想我在一个项目中做过类似的事情。我写的是这样的:
public interface IControllerBaseService
{
IUserService UserService {get;set;}
ShoppingMode ShoppingMode {get;set;}
...
}
public abstract class ControllerBase : Controller, IControllerBaseService
{
public IUserService UserService {get;set;} // this is injected by IoC
public ShoppingMode ShoppingMode
{
get
{
return UserService.CurrentShoppingMode; // this uses injected instance to get value
}
...
}
只要我使用IoC容器来创建控制器实例,UserService属性就会被容器注入。
你现在可以从视图访问你的接口,像这样:
(IControllerBaseService)ViewContext.Controller
为IControllerBaseService
中最常用的属性提供快捷方式,我有几个扩展方法,像这样:
public static ShoppingMode CurrentShoppingMode(this HtmlHelper helper)
{
return ((IContollerBaseService)helper.ViewContext.Controller).ShoppingMode;
}
所以在视图中它是@Html.CurrentShoppingMode()