Best way to expose cached objects to the views

佐手、 提交于 2019-12-10 22:42:56

问题


I am using an Translator object (custom class) to expose website texts (the object stores texts from the database). The Translator object is stored in the cache, in the Application_Start() function.

My current use of the Translator object is:

  • I have a MasterViewModel

    public class MasterViewModel
    {
        public Translator Translator = HttpContext.Current.Cache.Get("Translator") as   Translator;
    }
    
  • Every view has a viewmodel, that inherents from MasterViewModel

    public class RandomViewModel : MasterViewModel
    {
    }
    
  • In my views i can use my Translator object

    @model ViewModels.RandomViewModel
    
    @Model.Translator.GetText(label)
    

I don't think this is a nice aproach. Is it a good idea to make a razor helper in App_Code, so that in my views i can use

    @Translate.GetText("RANDOM_TEXT")

This will be the Helper function (in Translate.cshtml)

    @helper GetText(string label)
    {
        Translator Translator = @Cache.Get("Translator") as Translator;
        @: Translator.GetTextByLabel(label);
    }

So my question is what is the best way of exposing a cached object to all my views. Is one of the above approaches good? Or should i go with another solution?

(I hope my english is okay, i am dutch)


回答1:


There are different ways you can achieve that but I'll create a base class by deriving from WebViewPage and force all the razor views inherit from this class.

public abstract class MyWebViewPageBase<T>: WebViewPage<T>
{
   private Translator _translator;

   protected override void InitializePage()
   { 
     _translator = Context.Cache.Get("Translator") as Translator;
   }

   public string Translate(string label)
   {
     if(_translator != null)
       return _translator.GetText(label);

     return "";
   }
}

Now I can inherit the MyWebViewPage in razor views through couple of ways:

The first approach is from every view you have to use the @inherits directive.

Ex.

// Index.cshtml
@inherits MyWebViewPageBase
@model ...

....

The other approach is a global way of setting the base page for all the views and for that you have to modify the web.config that exists in the Views folder.

You have to set the pageBaseType of pages element as below,

<pages pageBaseType="MyWebViewPageBase">

Now from any view you can simply call the translate method as below,

@Translate("RANDOM_TEXT")

Hope this helps!



来源:https://stackoverflow.com/questions/10945840/best-way-to-expose-cached-objects-to-the-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!