1 // Copyright 2004-2008 Castle Project - http://www.castleproject.org/
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle
.MonoRail
.Framework
18 using System
.Collections
.Generic
;
19 using System
.Threading
;
23 using Castle
.MonoRail
.Framework
.Container
;
24 using Castle
.MonoRail
.Framework
.Configuration
;
25 using Castle
.MonoRail
.Framework
.Descriptors
;
30 /// Coordinates the creation of new <see cref="MonoRailHttpHandler"/>
31 /// and uses the configuration to obtain the correct factories
34 public class MonoRailHttpHandlerFactory
: IHttpHandlerFactory
36 private readonly static string CurrentEngineContextKey
= "currentmrengineinstance";
37 private readonly static string CurrentControllerKey
= "currentmrcontroller";
38 private readonly static string CurrentControllerContextKey
= "currentmrcontrollercontext";
39 private readonly ReaderWriterLock locker
= new ReaderWriterLock();
41 private static IMonoRailConfiguration configuration
;
42 private static IMonoRailContainer mrContainer
;
43 private static IUrlTokenizer urlTokenizer
;
44 private static IEngineContextFactory engineContextFactory
;
45 private static IServiceProviderLocator serviceProviderLocator
;
46 private static IControllerFactory controllerFactory
;
47 private static IControllerContextFactory controllerContextFactory
;
48 private static IStaticResourceRegistry staticResourceRegistry
;
51 /// Initializes a new instance of the <see cref="MonoRailHttpHandlerFactory"/> class.
53 public MonoRailHttpHandlerFactory() : this(ServiceProviderLocator
.Instance
)
58 /// Initializes a new instance of the <see cref="MonoRailHttpHandlerFactory"/> class.
60 /// <param name="serviceLocator">The service locator.</param>
61 public MonoRailHttpHandlerFactory(IServiceProviderLocator serviceLocator
)
63 serviceProviderLocator
= serviceLocator
;
67 /// Returns an instance of a class that implements
68 /// the <see cref="T:System.Web.IHttpHandler"></see> interface.
70 /// <param name="context">An instance of the <see cref="T:System.Web.HttpContext"></see> class that provides references to intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
71 /// <param name="requestType">The HTTP data transfer method (GET or POST) that the client uses.</param>
72 /// <param name="url">The <see cref="P:System.Web.HttpRequest.RawUrl"></see> of the requested resource.</param>
73 /// <param name="pathTranslated">The <see cref="P:System.Web.HttpRequest.PhysicalApplicationPath"></see> to the requested resource.</param>
75 /// A new <see cref="T:System.Web.IHttpHandler"></see> object that processes the request.
77 public virtual IHttpHandler
GetHandler(HttpContext context
,
79 String url
, String pathTranslated
)
81 PerformOneTimeInitializationIfNecessary(context
);
85 HttpRequest req
= context
.Request
;
87 RouteMatch routeMatch
= (RouteMatch
) context
.Items
[RouteMatch
.RouteMatchKey
] ?? new RouteMatch();
89 UrlInfo urlInfo
= urlTokenizer
.TokenizeUrl(req
.FilePath
, req
.PathInfo
, req
.Url
, req
.IsLocal
, req
.ApplicationPath
);
91 if (urlInfo
.Area
== "MonoRail" && urlInfo
.Controller
== "Files")
93 return new ResourceFileHandler(urlInfo
, new DefaultStaticResourceRegistry());
96 // TODO: Identify requests for files (js files) and serve them directly bypassing the flow
98 IEngineContext engineContext
= engineContextFactory
.Create(mrContainer
, urlInfo
, context
, routeMatch
);
99 engineContext
.AddService(typeof(IEngineContext
), engineContext
);
101 IController controller
;
105 controller
= controllerFactory
.CreateController(urlInfo
.Area
, urlInfo
.Controller
);
107 catch(ControllerNotFoundException
)
109 return new NotFoundHandler(urlInfo
.Area
, urlInfo
.Controller
, engineContext
);
112 ControllerMetaDescriptor controllerDesc
=
113 mrContainer
.ControllerDescriptorProvider
.BuildDescriptor(controller
);
115 IControllerContext controllerContext
=
116 controllerContextFactory
.Create(urlInfo
.Area
, urlInfo
.Controller
, urlInfo
.Action
, controllerDesc
, routeMatch
);
118 engineContext
.CurrentController
= controller
;
119 engineContext
.CurrentControllerContext
= controllerContext
;
121 context
.Items
[CurrentEngineContextKey
] = engineContext
;
122 context
.Items
[CurrentControllerKey
] = controller
;
123 context
.Items
[CurrentControllerContextKey
] = controllerContext
;
125 if (IgnoresSession(controllerDesc
.ControllerDescriptor
))
127 return new SessionlessMonoRailHttpHandler(engineContext
, controller
, controllerContext
);
131 return new MonoRailHttpHandler(engineContext
, controller
, controllerContext
);
136 /// Enables a factory to reuse an existing handler instance.
138 /// <param name="handler">The <see cref="T:System.Web.IHttpHandler"></see> object to reuse.</param>
139 public virtual void ReleaseHandler(IHttpHandler handler
)
144 /// Resets the state (only used from test cases)
146 public void ResetState()
148 configuration
= null;
151 engineContextFactory
= null;
152 serviceProviderLocator
= null;
153 controllerFactory
= null;
154 controllerContextFactory
= null;
155 staticResourceRegistry
= null;
159 /// Gets or sets the configuration.
161 /// <value>The configuration.</value>
162 public IMonoRailConfiguration Configuration
164 get { return configuration; }
165 set { configuration = value; }
169 /// Gets or sets the container.
171 /// <value>The container.</value>
172 public IMonoRailContainer Container
174 get { return mrContainer; }
175 set { mrContainer = value; }
179 /// Gets or sets the service provider locator.
181 /// <value>The service provider locator.</value>
182 public IServiceProviderLocator ProviderLocator
184 get { return serviceProviderLocator; }
185 set { serviceProviderLocator = value; }
189 /// Gets or sets the URL tokenizer.
191 /// <value>The URL tokenizer.</value>
192 public IUrlTokenizer UrlTokenizer
194 get { return urlTokenizer; }
195 set { urlTokenizer = value; }
199 /// Gets or sets the engine context factory.
201 /// <value>The engine context factory.</value>
202 public IEngineContextFactory EngineContextFactory
204 get { return engineContextFactory; }
205 set { engineContextFactory = value; }
209 /// Gets or sets the controller factory.
211 /// <value>The controller factory.</value>
212 public IControllerFactory ControllerFactory
214 get { return controllerFactory; }
215 set { controllerFactory = value; }
219 /// Gets or sets the controller context factory.
221 /// <value>The controller context factory.</value>
222 public IControllerContextFactory ControllerContextFactory
224 get { return controllerContextFactory; }
225 set { controllerContextFactory = value; }
229 /// Checks whether we should ignore session for the specified controller.
231 /// <param name="controllerDesc">The controller desc.</param>
232 /// <returns></returns>
233 protected virtual bool IgnoresSession(ControllerDescriptor controllerDesc
)
235 return controllerDesc
.Sessionless
;
239 /// Creates the default service container.
241 /// <param name="userServiceProvider">The user service provider.</param>
242 /// <param name="appInstance">The app instance.</param>
243 /// <returns></returns>
244 protected virtual IMonoRailContainer
CreateDefaultMonoRailContainer(IServiceProviderEx userServiceProvider
, HttpApplication appInstance
)
246 DefaultMonoRailContainer container
= new DefaultMonoRailContainer(userServiceProvider
);
248 container
.UseServicesFromParent();
249 container
.InstallPrimordialServices();
250 container
.Configure(Configuration
);
252 FireContainerCreated(appInstance
, container
);
254 // Too dependent on Http and MR surroundings services to be moved to Container class
255 if (!container
.HasService
<IServerUtility
>())
257 container
.AddService
<IServerUtility
>(new ServerUtilityAdapter(appInstance
.Context
.Server
));
259 if (!container
.HasService
<IRoutingEngine
>())
261 container
.AddService
<IRoutingEngine
>(RoutingModuleEx
.Engine
);
264 container
.InstallMissingServices();
265 container
.StartExtensionManager();
267 FireContainerInitialized(appInstance
, container
);
272 #region Static accessors
275 /// Gets the current engine context.
277 /// <value>The current engine context.</value>
278 public static IEngineContext CurrentEngineContext
280 get { return HttpContext.Current.Items[CurrentEngineContextKey] as IEngineContext; }
284 /// Gets the current controller.
286 /// <value>The current controller.</value>
287 public static IController CurrentController
289 get { return HttpContext.Current.Items[CurrentControllerKey] as IController; }
293 /// Gets the current controller context.
295 /// <value>The current controller context.</value>
296 public static IControllerContext CurrentControllerContext
298 get { return HttpContext.Current.Items[CurrentControllerContextKey] as IControllerContext; }
303 private void PerformOneTimeInitializationIfNecessary(HttpContext context
)
305 locker
.AcquireReaderLock(Timeout
.Infinite
);
307 if (mrContainer
!= null)
309 locker
.ReleaseReaderLock();
313 locker
.UpgradeToWriterLock(Timeout
.Infinite
);
315 if (mrContainer
!= null) // remember remember the race condition
317 locker
.ReleaseWriterLock();
323 if (configuration
== null)
325 configuration
= ObtainConfiguration(context
.ApplicationInstance
);
328 IServiceProviderEx userServiceProvider
= serviceProviderLocator
.LocateProvider();
330 mrContainer
= CreateDefaultMonoRailContainer(userServiceProvider
, context
.ApplicationInstance
);
334 locker
.ReleaseWriterLock();
338 private void FireContainerCreated(HttpApplication instance
, DefaultMonoRailContainer container
)
340 IMonoRailContainerEvents events
= instance
as IMonoRailContainerEvents
;
344 events
.Created(container
);
348 private void FireContainerInitialized(HttpApplication instance
, DefaultMonoRailContainer container
)
350 IMonoRailContainerEvents events
= instance
as IMonoRailContainerEvents
;
354 events
.Initialized(container
);
358 private IMonoRailConfiguration
ObtainConfiguration(HttpApplication appInstance
)
360 IMonoRailConfiguration config
= MonoRailConfiguration
.GetConfig();
362 IMonoRailConfigurationEvents events
= appInstance
as IMonoRailConfigurationEvents
;
366 config
= config
?? new MonoRailConfiguration();
368 events
.Configure(config
);
373 throw new ApplicationException("You have to provide a small configuration to use " +
374 "MonoRail. This can be done using the web.config or " +
375 "your global asax (your class that extends HttpApplication) " +
376 "through the method MonoRail_Configure(IMonoRailConfiguration config). " +
377 "Check the samples or the documentation.");
383 private void EnsureServices()
385 if (urlTokenizer
== null)
387 urlTokenizer
= mrContainer
.UrlTokenizer
;
389 if (engineContextFactory
== null)
391 engineContextFactory
= mrContainer
.EngineContextFactory
;
393 if (controllerFactory
== null)
395 controllerFactory
= mrContainer
.ControllerFactory
;
397 if (controllerContextFactory
== null)
399 controllerContextFactory
= mrContainer
.ControllerContextFactory
;
401 if (staticResourceRegistry
== null)
403 staticResourceRegistry
= mrContainer
.StaticResourceRegistry
;
408 /// Handles the controller not found situation
410 public class NotFoundHandler
: IHttpHandler
412 private readonly string area
;
413 private readonly string controller
;
414 private readonly IEngineContext engineContext
;
417 /// Initializes a new instance of the <see cref="NotFoundHandler"/> class.
419 /// <param name="area">The area.</param>
420 /// <param name="controller">The controller.</param>
421 /// <param name="engineContext">The engine context.</param>
422 public NotFoundHandler(string area
, string controller
, IEngineContext engineContext
)
425 this.controller
= controller
;
426 this.engineContext
= engineContext
;
430 /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
432 /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
433 public void ProcessRequest(HttpContext context
)
435 engineContext
.Response
.StatusCode
= 404;
436 engineContext
.Response
.StatusDescription
= "Not found";
438 if (engineContext
.Services
.ViewEngineManager
.HasTemplate("rescues/404"))
440 Dictionary
<string, object> parameters
= new Dictionary
<string, object>();
442 engineContext
.Services
.ViewEngineManager
.Process("rescues/404", null, engineContext
.Response
.Output
, parameters
);
444 return; // gracefully handled
447 throw new ControllerNotFoundException(area
, controller
);
451 /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
454 /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.</returns>
455 public bool IsReusable
457 get { return false; }