Ejemplo n.º 1
0
        public void Intercept(IInvocation invocation)
        {
            invocation.Proceed();

            var method = invocation.Method.Name;

            if (method.StartsWith("set_"))
            {
                var field = method.Replace("set_", "");

                var proxy = invocation.Proxy as IModel;

                if (proxy != null)
                {
                    proxy.PropertyChangeList.Add(field);
                }

                // rule execution
                var model = ProxyUtil.GetUnproxiedInstance(proxy) as IModel;

                var ruleAttribute = model.GetType().GetProperty(field).GetCustomAttribute(typeof(ModelRuleAttribute)) as ModelRuleAttribute;

                if (ruleAttribute != null)
                {
                    var rule = Activator.CreateInstance(ruleAttribute.Rule) as IModelRule;

                    if (rule != null)
                    {
                        rule.Execute(invocation.Proxy, field);
                    }
                }
            }
        }
Ejemplo n.º 2
0
 protected override void ApplyDecommissionConcerns(object instance)
 {
     //we don't want to let windsor dispose the session and interfere with SessionScope owning the Session
     //the other way would be using PerWebRequest
     instance = ProxyUtil.GetUnproxiedInstance(instance);
     ApplyConcerns(Model.Lifecycle.DecommissionConcerns.Where(x => !(x is DisposalConcern)), instance);
 }
Ejemplo n.º 3
0
        protected virtual void SetUpProperties(object instance, CreationContext context)
        {
            instance = ProxyUtil.GetUnproxiedInstance(instance);
            var resolver = Kernel.Resolver;

            foreach (var property in Model.Properties)
            {
                var value = ObtainPropertyValue(context, property, resolver);
                if (value == null)
                {
                    continue;
                }

                var setMethod = property.Property.GetSetMethod();
                try
                {
                    setMethod.Invoke(instance, new[] { value });
                }
                catch (Exception ex)
                {
                    var message =
                        String.Format(
                            "Error setting property {0} on type {1}, Component id is {2}. See inner exception for more information.",
                            setMethod.Name, instance.GetType().FullName, Model.Name);
                    throw new ComponentActivatorException(message, ex);
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        ///   Set up public properties on the given instance
        /// </summary>
        /// <param name="instance">Object instance to update</param>
        /// <param name="context">Current creation context</param>
        protected override void SetUpProperties(object instance, CreationContext context)
        {
            instance = ProxyUtil.GetUnproxiedInstance(instance);
            IDependencyResolver resolver = Kernel.Resolver;

            string[] resolvableProperties = (string[])Model.ExtendedProperties[Constants.ResolvablePublicPropertiesKey];
            foreach (PropertySet property in Model.Properties)
            {
                if (!resolvableProperties.Contains(property.Dependency.DependencyKey))
                {
                    continue;
                }

                object value = ObtainPropertyValue(context, property, resolver);
                if (value == null)
                {
                    continue;
                }

                MethodInfo setMethod = property.Property.GetSetMethod();
                try
                {
                    setMethod.Invoke(instance, new[] { value });
                }
                catch (Exception ex)
                {
                    string message =
                        string.Format(
                            "Error setting property {1}.{0} in component {2}. See inner exception for more information. If you don't want Windsor to set this property you can do it by either decorating it with {3} or via registration API.",
                            property.Property.Name, instance.GetType().Name, Model.Name, typeof(DoNotWireAttribute).Name);
                    throw new ComponentActivatorException(message, ex, Model);
                }
            }
        }
        /// <summary>
        /// Source: http://www.symbolsource.org/Public/Metadata/NuGet/Project/Castle.Windsor/3.0.0.3001/Release/.NETFramework,Version%3Dv4.0,Profile%3DClient/Castle.Windsor/Castle.Windsor/MicroKernel/ComponentActivator/DefaultComponentActivator.cs?ImageName=Castle.Windsor
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="context"></param>
        protected override void SetUpProperties(object instance, CreationContext context)
        {
            instance = ProxyUtil.GetUnproxiedInstance(instance);
            var resolver = Kernel.Resolver;

            foreach (var property in Model.Properties)
            {
                var value = ObtainPropertyValue(context, property, resolver);
                if (value == null)
                {
                    continue;
                }

                var setMethod = property.Property.GetSetMethod();
                try
                {
                    setMethod.Invoke(instance, new[] { value });
                }
                catch (Exception ex)
                {
                    var message =
                        String.Format(
                            "Error setting property {1}.{0} in component {2}. See inner exception for more information. If you don't want Windsor to set this property you can do it by either decorating it with {3} or via registration API.",
                            property.Property.Name, instance.GetType().Name, Model.Name, typeof(DoNotWireAttribute).Name);
                    throw new ComponentActivatorException(message, ex, Model);
                }
            }
        }
Ejemplo n.º 6
0
 public object GetTarget(object proxy)
 {
     if (!ProxyUtil.IsProxy(proxy))
     {
         return(null);
     }
     return(ProxyUtil.GetUnproxiedInstance(proxy));
 }
Ejemplo n.º 7
0
        protected override object Instantiate(CreationContext context)
        {
            var factoryId     = (String)Model.ExtendedProperties["factoryId"];
            var factoryCreate = (String)Model.ExtendedProperties["factoryCreate"];

            var factoryHandler = Kernel.GetHandler(factoryId);

            if (factoryHandler == null)
            {
                var message = String.Format("You have specified a factory ('{2}') " +
                                            "for the component '{0}' {1} but the kernel does not have this " +
                                            "factory registered",
                                            Model.Name, Model.Implementation.FullName, factoryId);
                throw new FacilityException(message);
            }

            // Let's find out whether the create method is a static or instance method

            var factoryType = factoryHandler.ComponentModel.Implementation;

            var staticCreateMethod =
                factoryType.GetMethod(factoryCreate,
                                      BindingFlags.Public | BindingFlags.Static);

            if (staticCreateMethod != null)
            {
                return(Create(null, factoryId, staticCreateMethod, factoryCreate, context));
            }
            var factoryInstance = Kernel.Resolve <object>(factoryId);

            var instanceCreateMethod =
                factoryInstance.GetType().GetMethod(factoryCreate,
                                                    BindingFlags.Public | BindingFlags.Instance);

            if (instanceCreateMethod == null)
            {
                factoryInstance = ProxyUtil.GetUnproxiedInstance(factoryInstance);

                instanceCreateMethod =
                    factoryInstance.GetType().GetMethod(factoryCreate,
                                                        BindingFlags.Public | BindingFlags.Instance);
            }

            if (instanceCreateMethod != null)
            {
                return(Create(factoryInstance, factoryId, instanceCreateMethod, factoryCreate, context));
            }
            else
            {
                var message = String.Format("You have specified a factory " +
                                            "('{2}' - method to be called: {3}) " +
                                            "for the component '{0}' {1} but we couldn't find the creation method" +
                                            "(neither instance or static method with the name '{3}')",
                                            Model.Name, Model.Implementation.FullName, factoryId, factoryCreate);
                throw new FacilityException(message);
            }
        }
Ejemplo n.º 8
0
        protected virtual void ApplyDecommissionConcerns(object instance)
        {
            if (Model.Lifecycle.HasDecommissionConcerns == false)
            {
                return;
            }

            instance = ProxyUtil.GetUnproxiedInstance(instance);
            ApplyConcerns(Model.Lifecycle.DecommissionConcerns, instance);
        }
Ejemplo n.º 9
0
        protected override object Instantiate(CreationContext context)
        {
            var instance = base.Instantiate(context);

            var behavior = ProxyUtil.GetUnproxiedInstance(instance);
            var scope    = WcfUtils.GetScope(Model);

            WcfUtils.ExtendBehavior(Kernel, scope, behavior, context);

            return(instance);
        }
Ejemplo n.º 10
0
        protected virtual void ApplyCommissionConcerns(object instance)
        {
            if (Model.Lifecycle.HasCommissionConcerns == false)
            {
                return;
            }

            instance = ProxyUtil.GetUnproxiedInstance(instance);
            ApplyConcerns(Model.Lifecycle.CommissionConcerns
#if DOTNET35 || SILVERLIGHT
                          .ToArray()
#endif
                          , instance);
        }
Ejemplo n.º 11
0
        protected virtual void ApplyCommissionConcerns(object instance)
        {
            if (Model.Lifecycle.HasCommissionConcerns == false)
            {
                return;
            }

            instance = ProxyUtil.GetUnproxiedInstance(instance);
            if (instance == null)
            {
                // see http://issues.castleproject.org/issue/IOC-332 for details
                throw new NotSupportedException(string.Format("Can not apply commission concerns to component {0} because it appears to be a target-less proxy. Currently those are not supported.", Model.Name));
            }
            ApplyConcerns(Model.Lifecycle.CommissionConcerns, instance);
        }
Ejemplo n.º 12
0
        protected override void ApplyDecommissionConcerns(object instance)
        {
            if (!Model.Lifecycle.HasDecommissionConcerns)
            {
                return;
            }

            instance = ProxyUtil.GetUnproxiedInstance(instance);
            var filtered = Model
                           .Lifecycle
                           .DecommissionConcerns
                           .Where(x => !(x is DisposalConcern));

            ApplyConcerns(filtered, instance);
        }
Ejemplo n.º 13
0
        private static K9AbpRepositoryBase <TEntity, TPrimaryKey> GetUnproxiedType <TEntity, TPrimaryKey>(
            this IRepository <TEntity, TPrimaryKey> repository)
            where TEntity : class, IEntity <TPrimaryKey>
        {
            if (repository is K9AbpRepositoryBase <TEntity, TPrimaryKey> repositoryBase)
            {
                return(repositoryBase);
            }
            var result = ProxyUtil.GetUnproxiedInstance(repository) as K9AbpRepositoryBase <TEntity, TPrimaryKey>;

            if (result != null)
            {
                return(result);
            }
            throw new NotSupportedException();
        }
Ejemplo n.º 14
0
        internal static object UnwrapProxy(object proxy)
        {
            if (!ProxyUtil.IsProxy(proxy))
            {
                return(proxy);
            }

            try
            {
                return(ProxyUtil.GetUnproxiedInstance(proxy));
            }
            catch (Exception)
            {
                return(proxy);
            }
        }
Ejemplo n.º 15
0
        public static void Demo()
        {
            // Adding interception to an interface proxy.  Invoke() is hosted on a target class that is not inherited from
            var incSub = new IncumbentSubclass();

            incSub.Init("World!");
            var proxyGenerator = new ProxyGenerator();
            var altHello       = proxyGenerator.CreateInterfaceProxyWithTarget <IHello>(incSub, new MyInterceptor());

            // var altHello = proxyGenerator.CreateClassProxy<IncumbentSubclass>(cls, );
            Debug.Assert(altHello.Hello() == "World!");
            // Debug.Assert(((Incumbent)altHello).StuckWithThis() == "blah");  NOPE
            Debug.Assert(((Incumbent)ProxyUtil.GetUnproxiedInstance(altHello)).StuckWithThis() == "blah");

            // ProxyUtil.CreateDelegateToMixin<>()  Does not appear useful... an interface facet to a given object with Invoke()

            // Resulting proxy impl of an interface inherits from a given parent class... but cannot seem to initialize ?!
            // Actually... this is bugged.  Need 'WithoutTarget'
            var options = new ProxyGenerationOptions
            {
                BaseTypeForInterfaceProxy = typeof(IncumbentSubclass)
            };

            altHello = proxyGenerator.CreateInterfaceProxyWithTarget <IHello>(incSub, options, new MyInterceptor());
            incSub   = (IncumbentSubclass)altHello;
            incSub.Init("Bingo!");
            var helloResponse = altHello.Hello();

            // Debug.Assert(helloResponse == "Bingo!"); // why not?
            Debug.Assert(helloResponse == "World!"); // WHY?

            // completely skip target class !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            options = new ProxyGenerationOptions
            {
                BaseTypeForInterfaceProxy = typeof(Incumbent)
            };
            altHello = proxyGenerator.CreateInterfaceProxyWithoutTarget <IHello>(options, new MyMetaImpl("Yellow!"));
            Debug.Assert(((Incumbent)altHello).StuckWithThis() == "blah");
            Debug.Assert(altHello.Hello() == "Yellow!");

            // Hmmm.... this isn't going to work.  Seems like we need a no-arg constructor in proxy parent class.
            var incSub2 = new IncumbentSubclass2("this'll be interesting");

            proxyGenerator.CreateInterfaceProxyWithTarget(typeof(IHello), incSub2, new MyMetaImpl("Dolly!"));
        }
        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
                }
            }
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Returns dynamic proxy target object if this is a proxied object, otherwise returns the given object.
 /// </summary>
 public static object UnProxy(object obj)
 {
     return(ProxyUtil.GetUnproxiedInstance(obj));
 }
Ejemplo n.º 18
0
 public static T GetUnderlying <T>(T proxy)
 {
     return(ProxyUtil.IsProxy(proxy) ? (T)ProxyUtil.GetUnproxiedInstance(proxy) : proxy);
 }
Ejemplo n.º 19
0
        /// <summary>
        /// 属性注入
        /// </summary>
        /// <param name="context">容器</param>
        /// <param name="Parameters">参数</param>
        /// <param name="instance">实例</param>
        /// <param name="allowCircle">是否可以循环</param>
        private void DoAutoWired(IComponentContext context, IEnumerable <Parameter> Parameters, object instance, bool allowCircle)
        {
            if (instance == null)
            {
                return;
            }
            Type   instanceType = instance.GetType();
            object RealInstance = instance;

            if (ProxyUtil.IsProxy(instance))
            {
                RealInstance = ProxyUtil.GetUnproxiedInstance(instance);
                instanceType = ProxyUtil.GetUnproxiedType(instance);
            }

            if (RealInstance == null)
            {
                return;
            }
            var componentModelCacheSingleton = context.Resolve <ComponentModelCacheSingleton>();

            if (!componentModelCacheSingleton.ComponentModelCache.TryGetValue(instanceType, out ComponentModel model))
            {
                return;
            }
            //字段注入
            foreach (var field in model.AutowiredFieldInfoList)
            {
                // ReSharper disable once PossibleMultipleEnumeration
                var obj = field.Item2.ResolveField(field.Item1, context, Parameters, RealInstance, allowCircle);
                if (obj == null)
                {
                    if (field.Item2.Required)
                    {
                        throw new DependencyResolutionException(
                                  $"Autowire error,can not resolve class type:{instanceType.FullName},field name:{field.Item1.Name} "
                                  + (!string.IsNullOrEmpty(field.Item2.Name) ? $",with key:{field.Item2.Name}" : ""));
                    }
                    continue;
                }
                try
                {
                    field.Item1.GetReflector().SetValue(RealInstance, obj);
                }
                catch (Exception ex)
                {
                    throw new DependencyResolutionException(
                              $"Autowire error,can not resolve class type:{instanceType.FullName},field name:{field.Item1.Name} "
                              + (!string.IsNullOrEmpty(field.Item2.Name) ? $",with key:{field.Item2.Name}" : ""), ex);
                }
            }
            //属性注入
            foreach (var property in model.AutowiredPropertyInfoList)
            {
                // ReSharper disable once PossibleMultipleEnumeration
                var obj = property.Item2.ResolveProperty(property.Item1, context, Parameters, RealInstance, allowCircle);
                if (obj == null)
                {
                    if (property.Item2.Required)
                    {
                        throw new DependencyResolutionException(
                                  $"Autowire error,can not resolve class type:{instanceType.FullName},property name:{property.Item1.Name} "
                                  + (!string.IsNullOrEmpty(property.Item2.Name) ? $",with key:{property.Item2.Name}" : ""));
                    }
                    continue;
                }
                try
                {
                    property.Item1.GetReflector().SetValue(RealInstance, obj);
                }
                catch (Exception ex)
                {
                    throw new DependencyResolutionException(
                              $"Autowire error,can not resolve class type:{instanceType.FullName},property name:{property.Item1.Name} "
                              + (!string.IsNullOrEmpty(property.Item2.Name) ? $",with key:{property.Item2.Name}" : ""), ex);
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 动态注入打了value标签的值
        /// </summary>
        /// <typeparam name="TReflectionActivatorData"></typeparam>
        /// <typeparam name="TSingleRegistrationStyle"></typeparam>
        /// <param name="component"></param>
        /// <param name="registrar"></param>
        protected virtual void RegisterComponentValues <TReflectionActivatorData, TSingleRegistrationStyle>(ComponentModel component,
                                                                                                            IRegistrationBuilder <object, TReflectionActivatorData, TSingleRegistrationStyle> registrar)
            where TReflectionActivatorData : ReflectionActivatorData
            where TSingleRegistrationStyle : SingleRegistrationStyle
        {
            if (component == null)
            {
                throw new ArgumentNullException(nameof(component));
            }

            if (registrar == null)
            {
                throw new ArgumentNullException(nameof(registrar));
            }

            component.ValuePropertyInfoList = (from p in component.CurrentType.GetAllProperties()
                                               let va = p.GetCustomAttribute <Value>()
                                                        where va != null
                                                        select new Tuple <PropertyInfo, Value>(p, va)).ToList();

            component.ValueFieldInfoList = (from p in component.CurrentType.GetAllFields()
                                            let va = p.GetCustomAttribute <Value>()
                                                     where va != null
                                                     select new Tuple <FieldInfo, Value>(p, va)).ToList();

            if (!component.ValueFieldInfoList.Any() && !component.ValuePropertyInfoList.Any())
            {
                return;
            }

            //创建对象之后调用
            registrar.OnActivated(e =>
            {
                var instance = e.Instance;
                if (instance == null)
                {
                    return;
                }
                Type instanceType   = instance.GetType();
                object RealInstance = instance;
                if (ProxyUtil.IsProxy(instance))
                {
                    RealInstance = ProxyUtil.GetUnproxiedInstance(instance);
                    instanceType = ProxyUtil.GetUnproxiedType(instance);
                }

                if (RealInstance == null)
                {
                    return;
                }
                var componentModelCacheSingleton = e.Context.Resolve <ComponentModelCacheSingleton>();
                if (!componentModelCacheSingleton.ComponentModelCache.TryGetValue(instanceType, out ComponentModel model))
                {
                    return;
                }
                foreach (var field in model.ValueFieldInfoList)
                {
                    var value = field.Item2.ResolveFiled(field.Item1, e.Context);
                    if (value == null)
                    {
                        continue;
                    }
                    try
                    {
                        field.Item1.GetReflector().SetValue(RealInstance, value);
                    }
                    catch (Exception ex)
                    {
                        throw new DependencyResolutionException($"Value set error,can not resolve class type:{instanceType.FullName} =====>" +
                                                                $" ,fail resolve field value:{field.Item1.Name} "
                                                                + (!string.IsNullOrEmpty(field.Item2.value) ? $",with value:[{field.Item2.value}]" : ""), ex);
                    }
                }

                foreach (var property in model.ValuePropertyInfoList)
                {
                    var value = property.Item2.ResolveProperty(property.Item1, e.Context);
                    if (value == null)
                    {
                        continue;
                    }
                    try
                    {
                        property.Item1.GetReflector().SetValue(RealInstance, value);
                    }
                    catch (Exception ex)
                    {
                        throw new DependencyResolutionException($"Value set error,can not resolve class type:{instanceType.FullName} =====>" +
                                                                $" ,fail resolve property value:{property.Item1.Name} "
                                                                + (!string.IsNullOrEmpty(property.Item2.value) ? $",with value:[{property.Item2.value}]" : ""),
                                                                ex);
                    }
                }
            });
        }