Is this html helper thread safe?

2019-06-16 20:49发布

问题:

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

回答1:

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.