1 // Copyright 2004-2007 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
.ActiveRecord
.Framework
19 using Castle
.ActiveRecord
.Framework
.Scopes
;
22 /// HttpModule to set up a session for the request lifetime.
23 /// <seealso cref="SessionScope"/>
26 /// To install the module, you must:
28 /// <list type="number">
31 /// Add the module to the <c>httpModules</c> configuration section within <c>system.web</c>
37 public class SessionScopeWebModule
: IHttpModule
40 /// The key used to store the session in the context items
42 protected static readonly String SessionKey
= "SessionScopeWebModule.session";
45 /// Used to check whether the ThreadScopeInfo being used is suitable for a web environment
47 private static bool isWebConfigured
;
50 /// Initialize the module.
52 /// <param name="app">The app.</param>
53 public void Init(HttpApplication app
)
55 if (ActiveRecordBase
.holder
== null)
57 // Not properly initialized, most probably due to a container initialization failure
58 // We cannot throw an exception as it will hide the original error, so we just
59 // skip our process completely
64 app
.BeginRequest
+= new EventHandler(OnBeginRequest
);
65 app
.EndRequest
+= new EventHandler(OnEndRequest
);
67 isWebConfigured
= (ActiveRecordBase
.holder
.ThreadScopeInfo
is WebThreadScopeInfo
);
71 /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"></see>.
78 /// Called when request is started, create a session for the request
80 /// <param name="sender">The sender.</param>
81 /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
82 private void OnBeginRequest(object sender
, EventArgs e
)
86 HttpContext
.Current
.Items
.Add(SessionKey
, new SessionScope());
90 throw new ActiveRecordException("Seems that the framework isn't configured properly. (isWeb != true and SessionScopeWebModule is in use) Check the documentation for further information");
95 /// Called when the request ends, dipose of the scope
97 /// <param name="sender">The sender.</param>
98 /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
99 private void OnEndRequest(object sender
, EventArgs e
)
101 SessionScope session
= (SessionScope
) HttpContext
.Current
.Items
[SessionKey
];