MVC Razor ViewEngine not thread-safe?
Asked Answered
M

2

5

I currently have a .net mvc3 application that is responsible for managing similar views in multiple locations that also use the same controllers e.g site1/v1/views/index.cshtml and site1/v2/views/index.cshtml.

The way that this is handled is by creating a CustomControllerFactory that inherits from DefaultControllerFactory and in the CreateController method, clear the existing view engines and add a new custom viewEngine that specifies the view location formats based off the current url.

If the user lands on site1.com/v1/index.cshtml, the viewengine will specify the view locations of :

string versionDirectory = "v1";
ViewLocationFormats = new[]{ versionDirectory + "/Views/{0}.cshtml",
                             "/Views/{0}.cshtml",
                             "~/Shared/{0}.cshtml"
                            };

The problem that I am having is that if multiple users land on different pages at roughly the same time all the users will see the same view.

Initially i thought this was related to caching, but after explicitly setting usecache = false in the custom viewEngine, it seems like this has got more to do with the ViewEngines class not being thread safe.

Does anyone have any ideas about how I can accomplish a the same result, but in a different way?

thanks in advance.

Mortmain answered 18/2, 2011 at 22:16 Comment(1)
not sure how you're doing this but any static objects are shared across all requests - that might be related to your problem...Ftlb
P
9

The ViewEngines collection is a static collection and thus its values are shared across requests. What you are attempting to do is possible, but the way you are doing it is not correct.

One easy approach is to write a custom view engine that derives from the RazorViewEngine and override the FindView method. That method is called once per request. In your implementation, call base.FindView and then modify the result (if it's not null) to include the site information you need.

Scott Hanselman has a blog post that shows one example of looking in another location for views via a custom view engine. http://www.hanselman.com/blog/ABetterASPNETMVCMobileDeviceCapabilitiesViewEngine.aspx

Porbeagle answered 19/2, 2011 at 4:56 Comment(1)
FYI the source in that post has a major production bug in it, there's an updated version of his view engine at: bitbucket.org/shanselman/mobileviewengines/src/48310997a453/… regardless the original post and the new link I provided were key to me solving my poor choice to modify the base.ViewLocationFormats collection not understanding it was static as opposed to http request scoped that i mistakenly thought.Carat
E
1

The built-in view engines ARE thread-safe. Your problem is caching or your custom view-engine. Check the caching comments in the link in the other answer.

Electro answered 19/2, 2011 at 6:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.