1+ /*
2+ * Copyright (c) 2014, Facebook, Inc.
3+ * All rights reserved.
4+ *
5+ * This source code is licensed under the BSD-style license found in the
6+ * LICENSE file in the root directory of this source tree. An additional grant
7+ * of patent rights can be found in the PATENTS file in the same directory.
8+ */
9+
10+ using System ;
11+ using System . Linq ;
12+ using System . Web ;
13+ using React . TinyIoC ;
14+
15+ namespace React . Web . TinyIoC
16+ {
17+ /// <summary>
18+ /// Scopes IoC registrations to the context of an ASP.NET web request. All instantiated
19+ /// components will be automatically disposed at the end of the request.
20+ /// </summary>
21+ public class HttpContextLifetimeProvider : TinyIoCContainer . ITinyIoCObjectLifetimeProvider
22+ {
23+ /// <summary>
24+ /// Prefix to use on HttpContext items
25+ /// </summary>
26+ private const string PREFIX = "TinyIoC.HttpContext." ;
27+ /// <summary>
28+ /// Name of the key for this particular registration
29+ /// </summary>
30+ private readonly string _keyName = PREFIX + Guid . NewGuid ( ) ;
31+
32+ /// <summary>
33+ /// Gets the stored object if it exists, or null if not
34+ /// </summary>
35+ /// <returns>Object instance or null</returns>
36+ public object GetObject ( )
37+ {
38+ return HttpContext . Current . Items [ _keyName ] ;
39+ }
40+
41+ /// <summary>
42+ /// Store the object
43+ /// </summary>
44+ /// <param name="value">Object to store</param>
45+ public void SetObject ( object value )
46+ {
47+ HttpContext . Current . Items [ _keyName ] = value ;
48+ }
49+
50+ /// <summary>
51+ /// Release the object
52+ /// </summary>
53+ public void ReleaseObject ( )
54+ {
55+ var item = GetObject ( ) as IDisposable ;
56+
57+ if ( item != null )
58+ item . Dispose ( ) ;
59+
60+ SetObject ( null ) ;
61+ }
62+
63+ /// <summary>
64+ /// Disposes all instantiated components
65+ /// </summary>
66+ public static void DisposeAll ( )
67+ {
68+ var items = HttpContext . Current . Items ;
69+ var disposableItems = items . Keys . OfType < string > ( )
70+ . Where ( key => key . StartsWith ( PREFIX ) )
71+ . Select ( key => items [ key ] )
72+ . Where ( item => item is IDisposable ) ;
73+
74+ foreach ( var item in disposableItems )
75+ {
76+ ( ( IDisposable ) item ) . Dispose ( ) ;
77+ }
78+ }
79+ }
80+ }
0 commit comments