コード例 #1
0
        private void BuildBaseContainer()
        {
            _serviceMap = _dependencyContainer.GetServiceMap();

            var map = new DependencyMap();

            foreach (var dependency in _serviceMap.Keys)
            {
                map.AddService(dependency, _serviceMap[dependency]);
            }

            _baseContainer = map.CreateContainer();
        }
コード例 #2
0
        /// <summary>
        /// Attempts to get an instance of the given <paramref name="serviceType"/>.
        /// </summary>
        /// <param name="serviceType">The service type.</param>
        /// <param name="key">The service name.</param>
        /// <returns>An object instance that matches the given service type. This method will return null if that service isn't available.</returns>
        public object GetInstance(Type serviceType, string key)
        {
            if (!Contains(serviceType, key))
            {
                return(null);
            }

            // Compile the container that will be used
            // to satisfy the dependencies for the service type
            if (_baseContainer == null)
            {
                BuildBaseContainer();
            }

            // Use the existing container, if possible
            if (!_containerMap.ContainsKey(serviceType))
            {
                // Create a new container that constructs the service type
                // and redirects all other calls to the base container
                var map = new DependencyMap();
                var availableDependencies = _serviceMap.Keys;

                foreach (var dependency in availableDependencies)
                {
                    // The base container will handle all the other dependencies
                    map.AddDeferredService(dependency.ServiceName, dependency.ServiceType);
                }

                // Add the service type itself
                var arguments    = serviceType.GetGenericArguments();
                var concreteType = _genericTypeImplementation.MakeGenericType(arguments);
                Register(serviceType, concreteType, map);

                // Compile the container
                var container = map.CreateContainer();

                // Defer the other calls to the base container
                container.NextContainer = _baseContainer;

                _containerMap[serviceType] = container;
            }

            var result = _containerMap[serviceType].GetInstance(serviceType, key);

            if (result == null && NextContainer != this && NextContainer != null)
            {
                return(NextContainer.GetInstance(serviceType, key));
            }

            return(result);
        }