0

假设我有一个与每个尝试访问我的网站的用户相似的对象。一种 Session Scope 对象,它应该在我的整个“应用程序”内的每个视图/模型/控制器上都可见。

我想在调用页面并通过来自我自己的数据库的数据填充它时创建它。

比,在视图(例如)调用 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();
    }
}

比,对于每个 UserControl,都是这样的:

public partial class context_pippo_MyOwnUserControl : iUserControl

在 MVC 上我看不到每个控件的任何扩展,那么我怎样才能实现这种过程呢?我想摆脱在 Session 上存储元素的问题。

4

1 回答 1

0

如果我正确理解问题,我想我在一个项目中做了类似的事情。我有这样的事情:

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()

于 2013-06-05T13:31:21.073 回答