How to use ModuleLoader class of Telerik.JustMock.AutoMock.Ninject.Modules package

Best JustMockLite code snippet using Telerik.JustMock.AutoMock.Ninject.Modules.ModuleLoader

Run JustMockLite automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

StandardKernel.cs

Source: StandardKernel.cs Github

copy
1//-------------------------------------------------------------------------------
2// <copyright file="StandardKernel.cs" company="Ninject Project Contributors">
3//   Copyright (c) 2007-2009, Enkari, Ltd.
4//   Copyright (c) 2009-2011 Ninject Project Contributors
5//   Authors: Nate Kohari ([email protected])
6//            Remo Gloor ([email protected])
7//           
8//   Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL).
9//   you may not use this file except in compliance with one of the Licenses.
10//   You may obtain a copy of the License at
11//
12//       http://www.apache.org/licenses/LICENSE-2.0
13//   or
14//       http://www.microsoft.com/opensource/licenses.mspx
15//
16//   Unless required by applicable law or agreed to in writing, software
17//   distributed under the License is distributed on an "AS IS" BASIS,
18//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19//   See the License for the specific language governing permissions and
20//   limitations under the License.
21// </copyright>
22//-------------------------------------------------------------------------------
23
24namespace Telerik.JustMock.AutoMock.Ninject
25{
26    using System;
27    using Telerik.JustMock.AutoMock.Ninject.Activation;
28    using Telerik.JustMock.AutoMock.Ninject.Activation.Caching;
29    using Telerik.JustMock.AutoMock.Ninject.Activation.Strategies;
30    using Telerik.JustMock.AutoMock.Ninject.Components;
31    using Telerik.JustMock.AutoMock.Ninject.Injection;
32    using Telerik.JustMock.AutoMock.Ninject.Modules;
33    using Telerik.JustMock.AutoMock.Ninject.Planning;
34    using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings.Resolvers;
35    using Telerik.JustMock.AutoMock.Ninject.Planning.Strategies;
36    using Telerik.JustMock.AutoMock.Ninject.Selection;
37    using Telerik.JustMock.AutoMock.Ninject.Selection.Heuristics;
38
39    /// <summary>
40    /// The standard implementation of a kernel.
41    /// </summary>
42    public class StandardKernel : KernelBase
43    {
44        /// <summary>
45        /// Initializes a new instance of the <see cref="StandardKernel"/> class.
46        /// </summary>
47        /// <param name="modules">The modules to load into the kernel.</param>
48        public StandardKernel(params INinjectModule[] modules) : base(modules)
49        {
50        }
51
52        /// <summary>
53        /// Initializes a new instance of the <see cref="StandardKernel"/> class.
54        /// </summary>
55        /// <param name="settings">The configuration to use.</param>
56        /// <param name="modules">The modules to load into the kernel.</param>
57        public StandardKernel(INinjectSettings settings, params INinjectModule[] modules) : base(settings, modules)
58        {
59        }
60
61        /// <summary>
62        /// Gets the kernel.
63        /// </summary>
64        /// <value>The kernel.</value>
65        protected override IKernel KernelInstance
66        {
67            get
68            {
69                return this;
70            }
71        }
72
73        protected virtual bool ShouldAddComponent(Type component, Type implementation)
74        {
75            return true;
76        }
77
78        private void AddComponent<TComponent, TImplementation>()
79            where TComponent : INinjectComponent
80            where TImplementation : TComponent, INinjectComponent
81        {
82            if (ShouldAddComponent(typeof(TComponent), typeof(TImplementation)))
83            {
84                Components.Add<TComponent, TImplementation>();
85            }
86        }
87        
88        /// <summary>
89        /// Adds components to the kernel during startup.
90        /// </summary>
91        protected override void AddComponents()
92        {
93            AddComponent<IPlanner, Planner>();
94            AddComponent<IPlanningStrategy, ConstructorReflectionStrategy>();
95            AddComponent<IPlanningStrategy, PropertyReflectionStrategy>();
96            AddComponent<IPlanningStrategy, MethodReflectionStrategy>();
97
98            AddComponent<ISelector, Selector>();
99            AddComponent<IConstructorScorer, StandardConstructorScorer>();
100            AddComponent<IInjectionHeuristic, StandardInjectionHeuristic>();
101
102            AddComponent<IPipeline, Pipeline>();
103            if (!Settings.ActivationCacheDisabled)
104            {
105                AddComponent<IActivationStrategy, ActivationCacheStrategy>();
106            }
107
108            AddComponent<IActivationStrategy, PropertyInjectionStrategy>();
109            AddComponent<IActivationStrategy, MethodInjectionStrategy>();
110            AddComponent<IActivationStrategy, InitializableStrategy>();
111            AddComponent<IActivationStrategy, StartableStrategy>();
112            AddComponent<IActivationStrategy, BindingActionStrategy>();
113            AddComponent<IActivationStrategy, DisposableStrategy>();
114
115            AddComponent<IBindingResolver, StandardBindingResolver>();
116            AddComponent<IBindingResolver, OpenGenericBindingResolver>();
117
118            AddComponent<IMissingBindingResolver, DefaultValueBindingResolver>();
119            AddComponent<IMissingBindingResolver, SelfBindingResolver>();
120
121#if !NO_LCG
122            if (!Settings.UseReflectionBasedInjection)
123            {
124                AddComponent<IInjectorFactory, DynamicMethodInjectorFactory>();
125            }
126            else
127#endif
128            {
129                AddComponent<IInjectorFactory, ReflectionInjectorFactory>();
130            }
131
132            AddComponent<ICache, Cache>();
133            AddComponent<IActivationCache, ActivationCache>();
134            AddComponent<ICachePruner, GarbageCollectionCachePruner>();
135
136#if !NO_ASSEMBLY_SCANNING
137            AddComponent<IModuleLoader, ModuleLoader>();
138            AddComponent<IModuleLoaderPlugin, CompiledModuleLoaderPlugin>();
139            AddComponent<IAssemblyNameRetriever, AssemblyNameRetriever>();
140#endif
141        }
142    }
143}
144
Full Screen

ModuleLoader.cs

Source: ModuleLoader.cs Github

copy
1#region License
2// 
3// Author: Nate Kohari <[email protected]>
4// Copyright (c) 2007-2010, Enkari, Ltd.
5// 
6// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL).
7// See the file LICENSE.txt for details.
8// 
9#endregion
10#if !NO_ASSEMBLY_SCANNING
11#region Using Directives
12using System;
13using System.Collections.Generic;
14using System.IO;
15using System.Linq;
16using Telerik.JustMock.AutoMock.Ninject.Components;
17using Telerik.JustMock.AutoMock.Ninject.Infrastructure;
18#endregion
19
20namespace Telerik.JustMock.AutoMock.Ninject.Modules
21{
22    /// <summary>
23    /// Automatically finds and loads modules from assemblies.
24    /// </summary>
25    public class ModuleLoader : NinjectComponent, IModuleLoader
26    {
27        /// <summary>
28        /// Gets or sets the kernel into which modules will be loaded.
29        /// </summary>
30        public IKernel Kernel { get; private set; }
31
32        /// <summary>
33        /// Initializes a new instance of the <see cref="ModuleLoader"/> class.
34        /// </summary>
35        /// <param name="kernel">The kernel into which modules will be loaded.</param>
36        public ModuleLoader(IKernel kernel)
37        {
38            Ensure.ArgumentNotNull(kernel, "kernel");
39            Kernel = kernel;
40        }
41
42        /// <summary>
43        /// Loads any modules found in the files that match the specified patterns.
44        /// </summary>
45        /// <param name="patterns">The patterns to search.</param>
46        public void LoadModules(IEnumerable<string> patterns)
47        {
48            var plugins = Kernel.Components.GetAll<IModuleLoaderPlugin>();
49
50            var fileGroups = patterns
51                .SelectMany(pattern => GetFilesMatchingPattern(pattern))
52                .GroupBy(filename => Path.GetExtension(filename).ToLowerInvariant());
53
54            foreach (var fileGroup in fileGroups)
55            {
56                string extension = fileGroup.Key;
57                IModuleLoaderPlugin plugin = plugins.Where(p => p.SupportedExtensions.Contains(extension)).FirstOrDefault();
58
59                if (plugin != null)
60                    plugin.LoadModules(fileGroup);
61            }
62        }
63
64        private static IEnumerable<string> GetFilesMatchingPattern(string pattern)
65        {
66            return NormalizePaths(Path.GetDirectoryName(pattern))
67                    .SelectMany(path => Directory.GetFiles(path, Path.GetFileName(pattern)));
68        }
69
70        private static IEnumerable<string> NormalizePaths(string path)
71        {
72            return Path.IsPathRooted(path)
73                        ? new[] { Path.GetFullPath(path) }
74                        : GetBaseDirectories().Select(baseDirectory => Path.Combine(baseDirectory, path));
75        }
76
77        private static IEnumerable<string> GetBaseDirectories()
78        {
79            var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
80            var searchPath = AppDomain.CurrentDomain.RelativeSearchPath;
81
82            return String.IsNullOrEmpty(searchPath) 
83                ? new[] {baseDirectory} 
84                : searchPath.Split(new[] {Path.PathSeparator}, StringSplitOptions.RemoveEmptyEntries)
85                    .Select(path => Path.Combine(baseDirectory, path));
86        }
87    }
88}
89#endif //!NO_ASSEMBLY_SCANNING
Full Screen

KernelBase.cs

Source: KernelBase.cs Github

copy
1// 
2// Author: Nate Kohari <[email protected]>
3// Copyright (c) 2007-2010, Enkari, Ltd.
4// 
5// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL).
6// See the file LICENSE.txt for details.
7// 
8
9namespace Telerik.JustMock.AutoMock.Ninject
10{
11    using System;
12    using System.Collections.Generic;
13    using System.Linq;
14    using System.Reflection;
15    using Telerik.JustMock.AutoMock.Ninject.Activation;
16    using Telerik.JustMock.AutoMock.Ninject.Activation.Blocks;
17    using Telerik.JustMock.AutoMock.Ninject.Activation.Caching;
18    using Telerik.JustMock.AutoMock.Ninject.Components;
19    using Telerik.JustMock.AutoMock.Ninject.Infrastructure;
20    using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection;
21    using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language;
22    using Telerik.JustMock.AutoMock.Ninject.Modules;
23    using Telerik.JustMock.AutoMock.Ninject.Parameters;
24    using Telerik.JustMock.AutoMock.Ninject.Planning;
25    using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings;
26    using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings.Resolvers;
27    using Telerik.JustMock.AutoMock.Ninject.Syntax;
28
29    /// <summary>
30    /// The base implementation of an <see cref="IKernel"/>.
31    /// </summary>
32    public abstract class KernelBase : BindingRoot, IKernel
33    {
34        /// <summary>
35        /// Lock used when adding missing bindings.
36        /// </summary>
37        protected readonly object HandleMissingBindingLockObject = new object();        
38        
39        private readonly Multimap<Type, IBinding> bindings = new Multimap<Type, IBinding>();
40
41        private readonly Multimap<Type, IBinding> bindingCache = new Multimap<Type, IBinding>();
42
43        private readonly Dictionary<string, INinjectModule> modules = new Dictionary<string, INinjectModule>();
44
45        /// <summary>
46        /// Initializes a new instance of the <see cref="KernelBase"/> class.
47        /// </summary>
48        protected KernelBase()
49            : this(new ComponentContainer(), new NinjectSettings(), new INinjectModule[0])
50        {
51        }
52
53        /// <summary>
54        /// Initializes a new instance of the <see cref="KernelBase"/> class.
55        /// </summary>
56        /// <param name="modules">The modules to load into the kernel.</param>
57        protected KernelBase(params INinjectModule[] modules)
58            : this(new ComponentContainer(), new NinjectSettings(), modules)
59        {
60        }
61
62        /// <summary>
63        /// Initializes a new instance of the <see cref="KernelBase"/> class.
64        /// </summary>
65        /// <param name="settings">The configuration to use.</param>
66        /// <param name="modules">The modules to load into the kernel.</param>
67        protected KernelBase(INinjectSettings settings, params INinjectModule[] modules)
68            : this(new ComponentContainer(), settings, modules)
69        {
70        }
71
72        /// <summary>
73        /// Initializes a new instance of the <see cref="KernelBase"/> class.
74        /// </summary>
75        /// <param name="components">The component container to use.</param>
76        /// <param name="settings">The configuration to use.</param>
77        /// <param name="modules">The modules to load into the kernel.</param>
78        protected KernelBase(IComponentContainer components, INinjectSettings settings, params INinjectModule[] modules)
79        {
80            Ensure.ArgumentNotNull(components, "components");
81            Ensure.ArgumentNotNull(settings, "settings");
82            Ensure.ArgumentNotNull(modules, "modules");
83
84            this.Settings = settings;
85
86            this.Components = components;
87            components.Kernel = this;
88
89            this.AddComponents();
90
91            this.Bind<IKernel>().ToConstant(this).InTransientScope();
92            this.Bind<IResolutionRoot>().ToConstant(this).InTransientScope();
93
94#if !NO_ASSEMBLY_SCANNING
95            if (this.Settings.LoadExtensions)
96            {
97                this.Load(this.Settings.ExtensionSearchPatterns);
98            }
99#endif
100            this.Load(modules);
101        }
102
103        /// <summary>
104        /// Gets the kernel settings.
105        /// </summary>
106        public INinjectSettings Settings { get; private set; }
107
108        /// <summary>
109        /// Gets the component container, which holds components that contribute to Ninject.
110        /// </summary>
111        public IComponentContainer Components { get; private set; }
112
113        /// <summary>
114        /// Releases resources held by the object.
115        /// </summary>
116        public override void Dispose(bool disposing)
117        {
118            if (disposing && !IsDisposed)
119            {
120                if (this.Components != null)
121                {
122                    // Deactivate all cached instances before shutting down the kernel.
123                    var cache = this.Components.Get<ICache>();
124                    cache.Clear();
125
126                    this.Components.Dispose();
127                }
128            }
129
130            base.Dispose(disposing);
131        }
132
133        /// <summary>
134        /// Unregisters all bindings for the specified service.
135        /// </summary>
136        /// <param name="service">The service to unbind.</param>
137        public override void Unbind(Type service)
138        {
139            Ensure.ArgumentNotNull(service, "service");
140
141            this.bindings.RemoveAll(service);
142
143            lock (this.bindingCache)
144            {
145                this.bindingCache.Clear();
146            }
147        }
148
149        /// <summary>
150        /// Registers the specified binding.
151        /// </summary>
152        /// <param name="binding">The binding to add.</param>
153        public override void AddBinding(IBinding binding)
154        {
155            Ensure.ArgumentNotNull(binding, "binding");
156
157            this.AddBindings(new[] { binding });
158        }
159
160        /// <summary>
161        /// Unregisters the specified binding.
162        /// </summary>
163        /// <param name="binding">The binding to remove.</param>
164        public override void RemoveBinding(IBinding binding)
165        {
166            Ensure.ArgumentNotNull(binding, "binding");
167
168            this.bindings.Remove(binding.Service, binding);
169
170            lock (this.bindingCache)
171                this.bindingCache.Clear();
172        }
173
174        /// <summary>
175        /// Determines whether a module with the specified name has been loaded in the kernel.
176        /// </summary>
177        /// <param name="name">The name of the module.</param>
178        /// <returns><c>True</c> if the specified module has been loaded; otherwise, <c>false</c>.</returns>
179        public bool HasModule(string name)
180        {
181            Ensure.ArgumentNotNullOrEmpty(name, "name");
182            return this.modules.ContainsKey(name);
183        }
184
185        /// <summary>
186        /// Gets the modules that have been loaded into the kernel.
187        /// </summary>
188        /// <returns>A series of loaded modules.</returns>
189        public IEnumerable<INinjectModule> GetModules()
190        {
191            return this.modules.Values.ToArray();
192        }
193
194        /// <summary>
195        /// Loads the module(s) into the kernel.
196        /// </summary>
197        /// <param name="m">The modules to load.</param>
198        public void Load(IEnumerable<INinjectModule> m)
199        {
200            Ensure.ArgumentNotNull(m, "modules");
201
202            m = m.ToList();
203            foreach (INinjectModule module in m)
204            {
205                if (string.IsNullOrEmpty(module.Name))
206                {
207                    throw new NotSupportedException(ExceptionFormatter.ModulesWithNullOrEmptyNamesAreNotSupported());
208                }
209                
210                INinjectModule existingModule;
211
212                if (this.modules.TryGetValue(module.Name, out existingModule))
213                {
214                    throw new NotSupportedException(ExceptionFormatter.ModuleWithSameNameIsAlreadyLoaded(module, existingModule));
215                }
216
217                module.OnLoad(this);
218
219                this.modules.Add(module.Name, module);
220            }
221
222            foreach (INinjectModule module in m)
223            {
224                module.OnVerifyRequiredModules();
225            }
226        }
227
228#if !NO_ASSEMBLY_SCANNING
229        /// <summary>
230        /// Loads modules from the files that match the specified pattern(s).
231        /// </summary>
232        /// <param name="filePatterns">The file patterns (i.e. "*.dll", "modules/*.rb") to match.</param>
233        public void Load(IEnumerable<string> filePatterns)
234        {
235            var moduleLoader = this.Components.Get<IModuleLoader>();
236            moduleLoader.LoadModules(filePatterns);
237        }
238
239        /// <summary>
240        /// Loads modules defined in the specified assemblies.
241        /// </summary>
242        /// <param name="assemblies">The assemblies to search.</param>
243        public void Load(IEnumerable<Assembly> assemblies)
244        {
245            this.Load(assemblies.SelectMany(asm => asm.GetNinjectModules()));
246        }
247#endif //!NO_ASSEMBLY_SCANNING
248
249        /// <summary>
250        /// Unloads the plugin with the specified name.
251        /// </summary>
252        /// <param name="name">The plugin's name.</param>
253        public void Unload(string name)
254        {
255            Ensure.ArgumentNotNullOrEmpty(name, "name");
256
257            INinjectModule module;
258
259            if (!this.modules.TryGetValue(name, out module))
260            {
261                throw new NotSupportedException(ExceptionFormatter.NoModuleLoadedWithTheSpecifiedName(name));
262            }
263
264            module.OnUnload(this);
265
266            this.modules.Remove(name);
267        }
268
269        /// <summary>
270        /// Injects the specified existing instance, without managing its lifecycle.
271        /// </summary>
272        /// <param name="instance">The instance to inject.</param>
273        /// <param name="parameters">The parameters to pass to the request.</param>
274        public virtual void Inject(object instance, params IParameter[] parameters)
275        {
276            Ensure.ArgumentNotNull(instance, "instance");
277            Ensure.ArgumentNotNull(parameters, "parameters");
278
279            Type service = instance.GetType();
280
281            var planner = this.Components.Get<IPlanner>();
282            var pipeline = this.Components.Get<IPipeline>();
283
284            var binding = new Binding(service);
285            var request = this.CreateRequest(service, null, parameters, false, false);
286            var context = this.CreateContext(request, binding);
287
288            context.Plan = planner.GetPlan(service);
289
290            var reference = new InstanceReference { Instance = instance };
291            pipeline.Activate(context, reference);
292        }
293
294        /// <summary>
295        /// Deactivates and releases the specified instance if it is currently managed by Ninject.
296        /// </summary>
297        /// <param name="instance">The instance to release.</param>
298        /// <returns><see langword="True"/> if the instance was found and released; otherwise <see langword="false"/>.</returns>
299        public virtual bool Release(object instance)
300        {
301            Ensure.ArgumentNotNull(instance, "instance");
302            var cache = this.Components.Get<ICache>();
303            return cache.Release(instance);
304        }
305
306        /// <summary>
307        /// Determines whether the specified request can be resolved.
308        /// </summary>
309        /// <param name="request">The request.</param>
310        /// <returns><c>True</c> if the request can be resolved; otherwise, <c>false</c>.</returns>
311        public virtual bool CanResolve(IRequest request)
312        {
313            Ensure.ArgumentNotNull(request, "request");
314            return this.GetBindings(request.Service).Any(this.SatifiesRequest(request));
315        }
316
317        /// <summary>
318        /// Determines whether the specified request can be resolved.
319        /// </summary>
320        /// <param name="request">The request.</param>
321        /// <param name="ignoreImplicitBindings">if set to <c>true</c> implicit bindings are ignored.</param>
322        /// <returns>
323        ///     <c>True</c> if the request can be resolved; otherwise, <c>false</c>.
324        /// </returns>
325        public virtual bool CanResolve(IRequest request, bool ignoreImplicitBindings)
326        {
327            Ensure.ArgumentNotNull(request, "request");
328            return this.GetBindings(request.Service)
329                .Any(binding => (!ignoreImplicitBindings || !binding.IsImplicit) && this.SatifiesRequest(request)(binding));
330        }
331
332        /// <summary>
333        /// Resolves instances for the specified request. The instances are not actually resolved
334        /// until a consumer iterates over the enumerator.
335        /// </summary>
336        /// <param name="request">The request to resolve.</param>
337        /// <returns>An enumerator of instances that match the request.</returns>
338        public virtual IEnumerable<object> Resolve(IRequest request)
339        {
340            Ensure.ArgumentNotNull(request, "request");
341
342            var bindingPrecedenceComparer = this.GetBindingPrecedenceComparer();
343            var resolveBindings = Enumerable.Empty<IBinding>();
344
345            if (this.CanResolve(request) || this.HandleMissingBinding(request))
346            {
347                resolveBindings = this.GetBindings(request.Service)
348                                      .Where(this.SatifiesRequest(request));
349
350            }
351
352            if (!resolveBindings.Any())
353            {
354                if (request.IsOptional)
355                {
356                    return Enumerable.Empty<object>();
357                }
358
359                throw new ActivationException(ExceptionFormatter.CouldNotResolveBinding(request));
360            }
361
362            if (request.IsUnique)
363            {
364                resolveBindings = resolveBindings.OrderByDescending(b => b, bindingPrecedenceComparer).ToList();
365                var model = resolveBindings.First(); // the type (conditonal, implicit, etc) of binding we'll return
366                resolveBindings =
367                    resolveBindings.TakeWhile(binding => bindingPrecedenceComparer.Compare(binding, model) == 0);
368
369                if (resolveBindings.Count() > 1)
370                {
371                    if (request.IsOptional)
372                    {
373                        return Enumerable.Empty<object>();
374                    }
375
376                    var formattedBindings =
377                        from binding in resolveBindings
378                        let context = this.CreateContext(request, binding)
379                        select binding.Format(context);
380                    throw new ActivationException(ExceptionFormatter.CouldNotUniquelyResolveBinding(request, formattedBindings.ToArray()));
381                }
382            }
383
384            if(resolveBindings.Any(binding => !binding.IsImplicit))
385            {
386                resolveBindings = resolveBindings.Where(binding => !binding.IsImplicit);
387            }
388
389            return resolveBindings
390                .Select(binding => this.CreateContext(request, binding).Resolve());
391        }
392
393        /// <summary>
394        /// Creates a request for the specified service.
395        /// </summary>
396        /// <param name="service">The service that is being requested.</param>
397        /// <param name="constraint">The constraint to apply to the bindings to determine if they match the request.</param>
398        /// <param name="parameters">The parameters to pass to the resolution.</param>
399        /// <param name="isOptional"><c>True</c> if the request is optional; otherwise, <c>false</c>.</param>
400        /// <param name="isUnique"><c>True</c> if the request should return a unique result; otherwise, <c>false</c>.</param>
401        /// <returns>The created request.</returns>
402        public virtual IRequest CreateRequest(Type service, Func<IBindingMetadata, bool> constraint, IEnumerable<IParameter> parameters, bool isOptional, bool isUnique)
403        {
404            Ensure.ArgumentNotNull(service, "service");
405            Ensure.ArgumentNotNull(parameters, "parameters");
406
407            return new Request(service, constraint, parameters, null, isOptional, isUnique);
408        }
409
410        /// <summary>
411        /// Begins a new activation block, which can be used to deterministically dispose resolved instances.
412        /// </summary>
413        /// <returns>The new activation block.</returns>
414        public virtual IActivationBlock BeginBlock()
415        {
416            return new ActivationBlock(this);
417        }
418
419        /// <summary>
420        /// Gets the bindings registered for the specified service.
421        /// </summary>
422        /// <param name="service">The service in question.</param>
423        /// <returns>A series of bindings that are registered for the service.</returns>
424        public virtual IEnumerable<IBinding> GetBindings(Type service)
425        {
426            Ensure.ArgumentNotNull(service, "service");
427
428            lock (this.bindingCache)
429            {
430                if (!this.bindingCache.ContainsKey(service))
431                {
432                    var resolvers = this.Components.GetAll<IBindingResolver>();
433
434                    resolvers
435                        .SelectMany(resolver => resolver.Resolve(this.bindings, service))
436                        .Map(binding => this.bindingCache.Add(service, binding));
437                }
438
439                return this.bindingCache[service];
440            }
441        }
442
443        /// <summary>
444        /// Returns an IComparer that is used to determine resolution precedence.
445        /// </summary>
446        /// <returns>An IComparer that is used to determine resolution precedence.</returns>
447        protected virtual IComparer<IBinding> GetBindingPrecedenceComparer()
448        {
449            return new BindingPrecedenceComparer();
450        }
451
452        /// <summary>
453        /// Returns a predicate that can determine if a given IBinding matches the request.
454        /// </summary>
455        /// <param name="request">The request/</param>
456        /// <returns>A predicate that can determine if a given IBinding matches the request.</returns>
457        protected virtual Func<IBinding, bool> SatifiesRequest(IRequest request)
458        {
459            return binding => binding.Matches(request) && request.Matches(binding);
460        }
461
462        /// <summary>
463        /// Adds components to the kernel during startup.
464        /// </summary>
465        protected abstract void AddComponents();
466
467        /// <summary>
468        /// Attempts to handle a missing binding for a service.
469        /// </summary>
470        /// <param name="service">The service.</param>
471        /// <returns><c>True</c> if the missing binding can be handled; otherwise <c>false</c>.</returns>
472        [Obsolete]
473        protected virtual bool HandleMissingBinding(Type service)
474        {
475            return false;
476        }
477
478        /// <summary>
479        /// Attempts to handle a missing binding for a request.
480        /// </summary>
481        /// <param name="request">The request.</param>
482        /// <returns><c>True</c> if the missing binding can be handled; otherwise <c>false</c>.</returns>
483        protected virtual bool HandleMissingBinding(IRequest request)
484        {
485            Ensure.ArgumentNotNull(request, "request");
486
487#pragma warning disable 612,618
488            if (this.HandleMissingBinding(request.Service))
489            {
490                return true;
491            }
492#pragma warning restore 612,618
493
494            var components = this.Components.GetAll<IMissingBindingResolver>();
495            
496            // Take the first set of bindings that resolve.
497            var bindings = components
498                .Select(c => c.Resolve(this.bindings, request).ToList())
499                .FirstOrDefault(b => b.Any());
500
501            if (bindings == null)
502            {
503                return false;
504            }
505
506            lock (this.HandleMissingBindingLockObject)
507            {
508                if (!this.CanResolve(request))
509                {
510                    bindings.Map(binding => binding.IsImplicit = true);
511                    this.AddBindings(bindings);
512                }
513            }
514
515            return true;
516        }
517
518        /// <summary>
519        /// Returns a value indicating whether the specified service is self-bindable.
520        /// </summary>
521        /// <param name="service">The service.</param>
522        /// <returns><see langword="True"/> if the type is self-bindable; otherwise <see langword="false"/>.</returns>
523        [Obsolete]
524        protected virtual bool TypeIsSelfBindable(Type service)
525        {
526            return !service.IsInterface
527                && !service.IsAbstract
528                && !service.IsValueType
529                && service != typeof(string)
530                && !service.ContainsGenericParameters;
531        }
532
533        /// <summary>
534        /// Creates a context for the specified request and binding.
535        /// </summary>
536        /// <param name="request">The request.</param>
537        /// <param name="binding">The binding.</param>
538        /// <returns>The created context.</returns>
539        protected virtual IContext CreateContext(IRequest request, IBinding binding)
540        {
541            Ensure.ArgumentNotNull(request, "request");
542            Ensure.ArgumentNotNull(binding, "binding");
543
544            return new Context(this, request, binding, this.Components.Get<ICache>(), this.Components.Get<IPlanner>(), this.Components.Get<IPipeline>());
545        }
546
547        private void AddBindings(IEnumerable<IBinding> bindings)
548        {
549            bindings.Map(binding => this.bindings.Add(binding.Service, binding));
550
551            lock (this.bindingCache)
552                this.bindingCache.Clear();
553        }
554
555        object IServiceProvider.GetService(Type service)
556        {
557            return this.Get(service);
558        }
559
560        private class BindingPrecedenceComparer : IComparer<IBinding>
561        {
562            public int Compare(IBinding x, IBinding y)
563            {
564                if (x == y)
565                {
566                    return 0;
567                }
568
569                // Each function represents a level of precedence.
570                var funcs = new List<Func<IBinding, bool>>
571                            {
572                                b => b != null,       // null bindings should never happen, but just in case
573                                b => b.IsConditional, // conditional bindings > unconditional
574                                b => !b.Service.ContainsGenericParameters, // closed generics > open generics
575                                b => !b.IsImplicit,   // explicit bindings > implicit
576                            };
577
578                var q = from func in funcs
579                        let xVal = func(x)
580                        where xVal != func(y) 
581                        select xVal ? 1 : -1;
582
583                // returns the value of the first function that represents a difference
584                // between the bindings, or else returns 0 (equal)
585                return q.FirstOrDefault();
586            }
587        }
588    }
589}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)