コード例 #1
0
        /// <summary>
        /// Adds the an instance to the dependencies.
        /// </summary>
        /// <param name="serviceType">Type of the service to add.</param>
        /// <param name="instance">The instance of the service to add.</param>
        /// <param name="lifetime">The lifetime for the registration.</param>
        protected override void AddDependencyInstanceCore(Type serviceType, object instance, DependencyLifetime lifetime)
        {
            if (lifetime == DependencyLifetime.Transient)
            {
                return;
            }

            var  binding = _kernel.GetBindings(serviceType).FirstOrDefault();
            bool foundExistingBinding = (binding != null);

            if (binding == null)
            {
                binding = CreateBinding(serviceType, lifetime);
                _kernel.AddBinding(binding);
            }

            var builder = new BindingBuilder <object>(binding, _kernel);

            if (lifetime == DependencyLifetime.PerRequest)
            {
                if (foundExistingBinding && binding.Target != BindingTarget.Method)
                {
                    // A binding exists, but wasn't specified as an instance callback. Error!
                    throw new DependencyResolutionException("Cannot register an instance for a type already registered");
                }

                var store = GetStore();
                var key   = serviceType.GetKey();
                store[key] = instance;

                if (!foundExistingBinding)
                {
                    store.GetContextInstances().Add(new ContextStoreDependency(key, instance, new ContextStoreDependencyCleaner(_kernel)));
                }

                builder.ToMethod(c =>
                {
                    var ctxStore = GetStore();
                    return(ctxStore[serviceType.GetKey()]);
                });
            }
            else if (lifetime == DependencyLifetime.Singleton)
            {
                builder.ToConstant(instance).InSingletonScope();
            }
        }