Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Razor ViewEngine not thread-safe?

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.

like image 554
kfegen Avatar asked Feb 18 '11 22:02

kfegen


2 Answers

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

like image 186
Haacked Avatar answered Nov 15 '22 04:11

Haacked


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.

like image 35
jgauffin Avatar answered Nov 15 '22 04:11

jgauffin