【问题标题】:How can I spread custom object through my MVC application?如何通过我的 MVC 应用程序传播自定义对象?
【发布时间】:2013-06-05 13:13:40
【问题描述】:

假设每个尝试访问我的网站的用户都有一个相似的对象。 一种 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 上存储元素的问题。

【问题讨论】:

    标签: c# asp.net-mvc concurrency webforms


    【解决方案1】:

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

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

    【讨论】:

    • 假设我有 FamilyComponents 类,我应该在任何我想要的地方访问它(在每个视图上):我在哪里创建 FamilyComponents 的单个实例?在 ControllerBase 内部?你能给我一个聪明的例子吗?谢谢
    • 我已经稍微更新了我的答案,但一般来说,如果我在 IControllerBaseService 中有复杂的属性,它要么由 IoC 容器注入,要么使用注入的属性解析,如示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多