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
.MonoRail
.Framework
17 using System
.Collections
.Generic
;
22 /// Uses the HttpContext and the <see cref="IServiceProviderExAccessor"/>
23 /// to access the container instance.
25 public class ServiceProviderLocator
: IServiceProviderLocator
27 private static readonly ServiceProviderLocator instance
= new ServiceProviderLocator();
29 private readonly IList
<IAccessorStrategy
> locatorStrategies
= new List
<IAccessorStrategy
>();
32 /// Initializes a new instance of the <see cref="ServiceProviderLocator"/> class.
34 public ServiceProviderLocator()
36 AddLocatorStrategy(new ServiceProviderAccessorStrategy());
40 /// Gets the instance.
42 /// <value>The instance.</value>
43 public static ServiceProviderLocator Instance
45 get { return instance; }
49 /// Locates the service provider using the registered strategies.
51 /// <returns></returns>
52 public IServiceProviderEx
LocateProvider()
54 foreach(IAccessorStrategy strategy
in locatorStrategies
)
56 IServiceProviderEx serviceProvider
= strategy
.LocateProvider();
58 if (serviceProvider
!= null)
60 return serviceProvider
;
68 /// Adds a locator strategy.
70 /// <param name="strategy">The strategy.</param>
71 public void AddLocatorStrategy(IAccessorStrategy strategy
)
73 locatorStrategies
.Add(strategy
);
77 /// Abstract an approach to access a <see cref="IServiceProviderEx"/>
79 public interface IAccessorStrategy
82 /// Locates the provider.
84 /// <returns></returns>
85 IServiceProviderEx
LocateProvider();
89 /// Default strategy to access a service provider
91 public class ServiceProviderAccessorStrategy
: IAccessorStrategy
94 /// Locates the provider using the ApplicationInstance and casting it to
95 /// <see cref="IServiceProviderExAccessor"/>
97 /// <returns></returns>
98 public IServiceProviderEx
LocateProvider()
100 IServiceProviderExAccessor containerAccessor
=
101 HttpContext
.Current
.ApplicationInstance
as IServiceProviderExAccessor
;
103 if (containerAccessor
== null)
108 return containerAccessor
.ServiceProvider
;