views:

510

answers:

3

While investigating implementing my own IControllerFactory I looked into the the default implementation DefaultControllerFactory and was surprised to see the RequestContext property being set in the CreateController(...) method, and then being referenced in the GetControllerInstance(...) and GetControllerType(...) methods.

The reason for my surprise is that as the factory is instantiated at Application start-up that same instance is used for all requests, so if multiple requests are received at the same time you have no guarantee which requests RequestContext has been set to the property when you come to use it.

Is there a guarantee in the MVC framework that only one request will be serviced by the registered IControllerFactory at a time?

If I am missing something here please enlighten me, as the implementaiton of my controller will be simpler if I have state between method calls during a requests lifecycle.

Thanks.

EDIT:

The answers given are as I expected but miss the main point of the question. The fact is the DefautlControllerFactory supplied as a part of the MVC framework is storing the RequestContext as if it has state - look at the source.

I believe this to be wrong and am looking for clarification (which I think I have seeing as both answers agree with my thoughts). I have cross posted to thte ASP.NET MVC Forums.

A: 

Your question: Is there a guarantee in the MVC framework that only one request will be serviced by the registered IControllerFactory at a time?

Answer: No, you have to use locks to store state.

My question: Why do you want to store state in the controller factory?

Paco
A: 

No the Controller factory CreateController method is executed for each request. In application startup you are only suppose to set your default controller and creating a new controller factory is only three lines of code:

public class CommonServiceLocatorControllerFactory : DefaultControllerFactory

{
protected override IController GetControllerInstance(Type controllerType)
{
return (controllerType == null) ? base.GetControllerInstance(controllerType) : ServiceLocator.Current.GetInstance(controllerType) as IController;
} }

kazimanzurrashid
+1  A: 

Cross posting to the ASP.NET MVC forums reveals this to be a bug with the DefaultControllerFactory implementation.

See here for information:

http://forums.asp.net/t/1414677.aspx

http://forums.asp.net/t/1404189.aspx

The latter post however reveals that you can have a controller factory be instatiated on each request, in which case you can have state.

From the post...

ControllerBuilder.Current.SetControllerFactory(typeof(DefaultControllerFactory));

This will switch the mode of the controller builder from instance-based to type-based, and will create a new instance of the controller factory on every request.

crowleym