public EnvironmentScope()
 {
     _items              = new List <object>();
     _clear              = new HashSet <Type>();
     _keyValues          = new Dictionary <string, object>();
     _instanceIdentifier = new InstanceIdentifier();
     _parentScope        = GetAmbientScope();
     SetAmbientScope(this);
 }
        public void Intercept(IInvocation invocation)
        {
            var envScope = EnvironmentScope.GetAmbientScope();

            if (envScope != null)
            {
                BindEnvironment(invocation.Proxy, envScope);
            }
            invocation.Proceed();
        }
        internal static void SetAmbientScope(EnvironmentScope newAmbientScope)
        {
            var current = CallContext.LogicalGetData(AmbientScopeKey) as InstanceIdentifier;

            if (current == newAmbientScope._instanceIdentifier)
            {
                return;
            }

            CallContext.LogicalSetData(AmbientScopeKey, newAmbientScope._instanceIdentifier);

            AppDomainInstances.GetValue(newAmbientScope._instanceIdentifier, key => newAmbientScope);
        }
        public bool CanResolve(CreationContext context,
                               ISubDependencyResolver contextHandlerResolver, ComponentModel model,
                               DependencyModel dependency)
        {
            var envScope = EnvironmentScope.GetAmbientScope();

            if (envScope == null)
            {
                return(false);
            }

            var key  = dependency.DependencyKey;
            var type = dependency.TargetItemType;

            return(envScope.HasKey(key, type) || envScope.Contains(type));
        }
        private void BindEnvironment(object instance, EnvironmentScope envScope)
        {
            var resolver = _kernel.Resolver;
            var context  = CreationContext.CreateEmpty();

            instance = ProxyUtil.GetUnproxiedInstance(instance);

            foreach (var property in _componentModel.Properties
                     .Where(property => envScope.Contains(property.Property.PropertyType)))
            {
                try
                {
                    var value = resolver.Resolve(context, context.Handler, _componentModel, property.Dependency);
                    if (value == null)
                    {
                        continue;
                    }
                    if (value == EnvironmentScope.Null)
                    {
                        value = null;
                    }
                    try
                    {
                        var setMethod = property.Property.GetSetMethod();
                        setMethod.Invoke(instance, new[] { value });
                    }
                    catch
                    {
                        // ignore
                    }
                }
                catch
                {
                    // ignore
                }
            }
        }