9

I am wondering if the code as referenced as the accepted answer on this link is thread safe. I mean not for multi threading. I just dont want output crossing user page requests.
Add CSS or JavaScript files to layout head from views or partial views

Would I have a situation where many requests to a page could have crossed over styles and scripts.

It may help if you have knowledge of MVC in that the add methods are called as views are rendered and the result is rendered to the layout (master page).

Current Solution (Please let me know if it should be improved)

public static MyCompanyHtmlHelpers GetInstance(HtmlHelper htmlHelper)
{
    MyCompanyHtmlHelpers _instance;
    if (htmlHelper.ViewData["SectionHelper"] == null)
    {
        _instance = new MyCompanyHtmlHelpers();
        htmlHelper.ViewData["SectionHelper"] = _instance;
    }
    else
        _instance = htmlHelper.ViewData["SectionHelper"] as MyCompanyHtmlHelpers;

    _instance.SetHtmlHelper(htmlHelper);

    return _instance;
}

thanks

Community
  • 1
  • 1
Valamas
  • 24,169
  • 25
  • 107
  • 177

1 Answers1

6

Hmm.... doesn't look like it to me ;p

HtmlHelper has some instance properties, in particular ViewContext and ViewData (via ViewDataContainer) etc. Putting that anywhere static is a terrible terrible idea.

With the basic code that is going on you'll probably get away with it, but: IMO this is still a very bad idea. Well spotted.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • darn, i really like this solution. Can it be made thread safe? – Valamas Jul 07 '11 at 11:11
  • @Valams in particular, the helper's ViewContext has a HttpContext; from that you can store anything. ***That*** is what I would use for storage here. – Marc Gravell Jul 07 '11 at 11:14
  • thank you very much! i am off now researching how to do that as I have not had much exposure. – Valamas Jul 07 '11 at 11:23
  • 3
    @Valamas, @Marc sorry about the late reply (I was on holiday). A few weeks earlier we realized that code is not thread-safe. So I have changed that static/singleton implementation and we are storing the actual instance in the current HttpContext. Also in the meantime I have started working on a simple project for handling assets. You can take look at here: https://github.com/speier/AssetBox it's much like an experiment, it was the base of the current solution what we are using at my workplace. Let me know what do you think. – Kalman Speier Jul 14 '11 at 15:50
  • Not terribly helpful to update the question so that the accepted answer no longer makes sense... – Silas Davis Apr 11 '12 at 15:52