PageRenderTime 75ms CodeModel.GetById 71ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/src/CommonServiceLocator/CommonServiceLocator.LinFuAdapter/LinFuServiceLocator.cs

http://github.com/philiplaureano/LinFu
C# | 58 lines | 46 code | 11 blank | 1 comment | 12 complexity | ebb6c00309fcb420d828dfdcb4e6ca8d MD5 | raw file
 1using System;
 2using System.Collections;
 3using System.Collections.Generic;
 4using System.Linq;
 5
 6using LinFu.IoC;
 7using LinFu.IoC.Configuration;
 8using LinFu.IoC.Interfaces;
 9using Microsoft.Practices.ServiceLocation;
10
11namespace CommonServiceLocator.LinFuAdapter
12{
13    public sealed class LinFuServiceLocator : ServiceLocatorImplBase
14    {
15        readonly IServiceContainer _container;
16
17        public LinFuServiceLocator(IServiceContainer container)
18        {
19            if (container == null)
20                throw new ArgumentNullException("container");
21
22            _container = container;
23        }
24
25        protected override object DoGetInstance(Type serviceType, string key)
26        {
27            if (key != null)
28                return _container.GetService(key, serviceType);
29
30            // Return the first service if nothing else can be found
31            Func<IServiceInfo, bool> criteria = info =>
32                {
33                    var matchesServiceType = info.ServiceType == serviceType;
34
35                    if (!matchesServiceType)
36                        return false;
37
38                    return info.ArgumentTypes == null || info.ArgumentTypes.Count() == 0;
39                };
40
41            var defaultService = _container.AvailableServices.Where(criteria).FirstOrDefault();
42            return _container.GetService(defaultService);
43        }
44
45        protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
46        {
47            Func<IServiceInfo, bool> matchesServiceType = info => serviceType == info.ServiceType &&
48                                                                  (info.ArgumentTypes == null ||
49                                                                   info.ArgumentTypes.Count() == 0);
50
51            var services = _container.AvailableServices.Where(matchesServiceType);
52            foreach (var service in services)
53            {
54                yield return _container.GetService(service);
55            }
56        }
57    }
58}