Removed untyped contructor from ComponentRegistration and add a protected setter.
[castle.git] / MonoRail / Castle.MonoRail.Framework / MonoRailHttpHandlerFactory.cs
blobb527925bbf4322d8509866a27e6ae8536d55cb5c
1 // Copyright 2004-2008 Castle Project - http://www.castleproject.org/
2 //
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
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
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
17 using System;
18 using System.Collections.Generic;
19 using System.Threading;
20 using System.Web;
21 using Adapters;
22 using Castle.Core;
23 using Castle.MonoRail.Framework.Container;
24 using Castle.MonoRail.Framework.Configuration;
25 using Castle.MonoRail.Framework.Descriptors;
26 using Routing;
27 using Services;
29 /// <summary>
30 /// Coordinates the creation of new <see cref="MonoRailHttpHandler"/>
31 /// and uses the configuration to obtain the correct factories
32 /// instances.
33 /// </summary>
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;
50 /// <summary>
51 /// Initializes a new instance of the <see cref="MonoRailHttpHandlerFactory"/> class.
52 /// </summary>
53 public MonoRailHttpHandlerFactory() : this(ServiceProviderLocator.Instance)
57 /// <summary>
58 /// Initializes a new instance of the <see cref="MonoRailHttpHandlerFactory"/> class.
59 /// </summary>
60 /// <param name="serviceLocator">The service locator.</param>
61 public MonoRailHttpHandlerFactory(IServiceProviderLocator serviceLocator)
63 serviceProviderLocator = serviceLocator;
66 /// <summary>
67 /// Returns an instance of a class that implements
68 /// the <see cref="T:System.Web.IHttpHandler"></see> interface.
69 /// </summary>
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>
74 /// <returns>
75 /// A new <see cref="T:System.Web.IHttpHandler"></see> object that processes the request.
76 /// </returns>
77 public virtual IHttpHandler GetHandler(HttpContext context,
78 String requestType,
79 String url, String pathTranslated)
81 PerformOneTimeInitializationIfNecessary(context);
83 EnsureServices();
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);
129 else
131 return new MonoRailHttpHandler(engineContext, controller, controllerContext);
135 /// <summary>
136 /// Enables a factory to reuse an existing handler instance.
137 /// </summary>
138 /// <param name="handler">The <see cref="T:System.Web.IHttpHandler"></see> object to reuse.</param>
139 public virtual void ReleaseHandler(IHttpHandler handler)
143 /// <summary>
144 /// Resets the state (only used from test cases)
145 /// </summary>
146 public void ResetState()
148 configuration = null;
149 mrContainer = null;
150 urlTokenizer = null;
151 engineContextFactory = null;
152 serviceProviderLocator = null;
153 controllerFactory = null;
154 controllerContextFactory = null;
155 staticResourceRegistry = null;
158 /// <summary>
159 /// Gets or sets the configuration.
160 /// </summary>
161 /// <value>The configuration.</value>
162 public IMonoRailConfiguration Configuration
164 get { return configuration; }
165 set { configuration = value; }
168 /// <summary>
169 /// Gets or sets the container.
170 /// </summary>
171 /// <value>The container.</value>
172 public IMonoRailContainer Container
174 get { return mrContainer; }
175 set { mrContainer = value; }
178 /// <summary>
179 /// Gets or sets the service provider locator.
180 /// </summary>
181 /// <value>The service provider locator.</value>
182 public IServiceProviderLocator ProviderLocator
184 get { return serviceProviderLocator; }
185 set { serviceProviderLocator = value; }
188 /// <summary>
189 /// Gets or sets the URL tokenizer.
190 /// </summary>
191 /// <value>The URL tokenizer.</value>
192 public IUrlTokenizer UrlTokenizer
194 get { return urlTokenizer; }
195 set { urlTokenizer = value; }
198 /// <summary>
199 /// Gets or sets the engine context factory.
200 /// </summary>
201 /// <value>The engine context factory.</value>
202 public IEngineContextFactory EngineContextFactory
204 get { return engineContextFactory; }
205 set { engineContextFactory = value; }
208 /// <summary>
209 /// Gets or sets the controller factory.
210 /// </summary>
211 /// <value>The controller factory.</value>
212 public IControllerFactory ControllerFactory
214 get { return controllerFactory; }
215 set { controllerFactory = value; }
218 /// <summary>
219 /// Gets or sets the controller context factory.
220 /// </summary>
221 /// <value>The controller context factory.</value>
222 public IControllerContextFactory ControllerContextFactory
224 get { return controllerContextFactory; }
225 set { controllerContextFactory = value; }
228 /// <summary>
229 /// Checks whether we should ignore session for the specified controller.
230 /// </summary>
231 /// <param name="controllerDesc">The controller desc.</param>
232 /// <returns></returns>
233 protected virtual bool IgnoresSession(ControllerDescriptor controllerDesc)
235 return controllerDesc.Sessionless;
238 /// <summary>
239 /// Creates the default service container.
240 /// </summary>
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);
269 return container;
272 #region Static accessors
274 /// <summary>
275 /// Gets the current engine context.
276 /// </summary>
277 /// <value>The current engine context.</value>
278 public static IEngineContext CurrentEngineContext
280 get { return HttpContext.Current.Items[CurrentEngineContextKey] as IEngineContext; }
283 /// <summary>
284 /// Gets the current controller.
285 /// </summary>
286 /// <value>The current controller.</value>
287 public static IController CurrentController
289 get { return HttpContext.Current.Items[CurrentControllerKey] as IController; }
292 /// <summary>
293 /// Gets the current controller context.
294 /// </summary>
295 /// <value>The current controller context.</value>
296 public static IControllerContext CurrentControllerContext
298 get { return HttpContext.Current.Items[CurrentControllerContextKey] as IControllerContext; }
301 #endregion
303 private void PerformOneTimeInitializationIfNecessary(HttpContext context)
305 locker.AcquireReaderLock(Timeout.Infinite);
307 if (mrContainer != null)
309 locker.ReleaseReaderLock();
310 return;
313 locker.UpgradeToWriterLock(Timeout.Infinite);
315 if (mrContainer != null) // remember remember the race condition
317 locker.ReleaseWriterLock();
318 return;
323 if (configuration == null)
325 configuration = ObtainConfiguration(context.ApplicationInstance);
328 IServiceProviderEx userServiceProvider = serviceProviderLocator.LocateProvider();
330 mrContainer = CreateDefaultMonoRailContainer(userServiceProvider, context.ApplicationInstance);
332 finally
334 locker.ReleaseWriterLock();
338 private void FireContainerCreated(HttpApplication instance, DefaultMonoRailContainer container)
340 IMonoRailContainerEvents events = instance as IMonoRailContainerEvents;
342 if (events != null)
344 events.Created(container);
348 private void FireContainerInitialized(HttpApplication instance, DefaultMonoRailContainer container)
350 IMonoRailContainerEvents events = instance as IMonoRailContainerEvents;
352 if (events != null)
354 events.Initialized(container);
358 private IMonoRailConfiguration ObtainConfiguration(HttpApplication appInstance)
360 IMonoRailConfiguration config = MonoRailConfiguration.GetConfig();
362 IMonoRailConfigurationEvents events = appInstance as IMonoRailConfigurationEvents;
364 if (events != null)
366 config = config ?? new MonoRailConfiguration();
368 events.Configure(config);
371 if (config == null)
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.");
380 return config;
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;
407 /// <summary>
408 /// Handles the controller not found situation
409 /// </summary>
410 public class NotFoundHandler : IHttpHandler
412 private readonly string area;
413 private readonly string controller;
414 private readonly IEngineContext engineContext;
416 /// <summary>
417 /// Initializes a new instance of the <see cref="NotFoundHandler"/> class.
418 /// </summary>
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)
424 this.area = area;
425 this.controller = controller;
426 this.engineContext = engineContext;
429 /// <summary>
430 /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
431 /// </summary>
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);
450 /// <summary>
451 /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
452 /// </summary>
453 /// <value></value>
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; }