public async void OnActivatingScp914(ActivatingEventArgs ev)
 {
     if (Instance.Config.EventsToLog.ActivatingScp914 && (!ev.Player.DoNotTrack || !Instance.Config.ShouldRespectDoNotTrack))
     {
         await Network.SendAsync(new RemoteCommand("log", "gameEvents", string.Format(Language.Scp914HasBeenActivated, ev.Player.Nickname, Instance.Config.ShouldLogUserIds ? ev.Player.UserId : Language.Redacted, ev.Player.Role, Scp914Machine.singleton.knobState))).ConfigureAwait(false);
     }
 }
示例#2
0
        /// <summary>
        /// Registrations the activating.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="object"/> instance containing the event data.</param>
        private void RegistrationActivating(object sender, ActivatingEventArgs <object> e)
        {
            // Ignore AspectConfiguration and IInterceptor types since they're being referenced via the Autofac
            // registration context. Otherwise calling e.Context.Resolve<IInterceptor> will fail when
            // the code below executes.

            var masterProxy = e.Instance as MasterProxy;

            if (masterProxy != null)
            {
                // for master proxy we need to assign reference to current container, which is used to resolve aspects from
                // AutofacServiceLocatorAdapter cannot be built just with e.Context despite fact that e.Context is of IComponentContext
                // e.Context is valid only in scope of current instance activation
                // To get valid IComponentContext we need to resolve it in the following way
                (masterProxy).Container = new AutofacServiceLocatorAdapter(e.Context.Resolve <IComponentContext>());
                return;
            }

            // inteceptors could not be intercepted too, thus skip the code below
            if (e.Instance is IInterceptor)
            {
                return;
            }

            var proxy = (MasterProxy)e.Context.Resolve(typeof(MasterProxy));

            if (!e.Instance.IsDecorated(proxy.Configuration))
            {
                return;
            }

            e.Instance = _proxyFactory.CreateProxy(e.Instance, proxy);
        }
示例#3
0
        /// <summary>
        /// Registrations the activating.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Autofac.Core.ActivatingEventArgs&lt;System.Object&gt;"/> instance containing the event data.</param>
        private static void RegistrationActivating(object sender, ActivatingEventArgs<object> e)
        {
            // Ignore AspectConfiguration and IInterceptor types since they're being referenced via the Autofac
            // registration context. Otherwise calling e.Context.Resolve<IInterceptor> will fail when
            // the code below executes.
            if (e.Instance.GetType() == typeof (AspectConfiguration) || e.Instance is IInterceptor)
            {
                return;
            }

            var components = e.Context.ComponentRegistry.Registrations
                .Where(r => r.Target.Services.Any(s => s.Description.Contains("IInterceptor")))
                .SelectMany(svc => svc.Services)
                    .Where(i => i.Description != "Castle.Core.Interceptor.IInterceptor")
                .Select(interceptor => interceptor);

            var config = e.Context.Resolve<AspectConfiguration>();
            var type = e.Instance.GetType();
            var interfaceTypes = type.GetInterfaces();

            var namespaces = config.Namespaces;

            // Filter the interfaces by given namespaces that implement IInterceptAspect
            var targetInterface = interfaceTypes.FirstOrDefault(i => namespaces.Any(n => i.FullName.Contains(n)) &&
                                                                     i.FullName != "Snap.IInterceptAspect");

            var interceptors = new List<IInterceptor>();

            components.ToList().ForEach(i => interceptors.Add(e.Context.Resolve(i) as IInterceptor));

            e.Instance = AspectUtility.CreateProxy(targetInterface, e.Instance, interceptors.ToArray());
        }
示例#4
0
        /// <summary>
        /// Registrations the activating.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="object"/> instance containing the event data.</param>
        private void RegistrationActivating(object sender, ActivatingEventArgs<object> e)
        {
            // Ignore AspectConfiguration and IInterceptor types since they're being referenced via the Autofac
            // registration context. Otherwise calling e.Context.Resolve<IInterceptor> will fail when
            // the code below executes.

            var masterProxy = e.Instance as MasterProxy;
            if (masterProxy != null)
            {
                // for master proxy we need to assign reference to current container, which is used to resolve aspects from
                // AutofacServiceLocatorAdapter cannot be built just with e.Context despite fact that e.Context is of IComponentContext
                // e.Context is valid only in scope of current instance activation
                // To get valid IComponentContext we need to resolve it in the following way
                (masterProxy).Container = new AutofacServiceLocatorAdapter(e.Context.Resolve<IComponentContext>());
                return;
            }

            // inteceptors could not be intercepted too, thus skip the code below
            if (e.Instance is IInterceptor)
            {
                return;
            }

            var proxy = (MasterProxy)e.Context.Resolve(typeof(MasterProxy));

            if (!e.Instance.IsDecorated(proxy.Configuration))
            {
                return;
            }

            e.Instance = _proxyFactory.CreateProxy(e.Instance, proxy);
        }
示例#5
0
        private void Registration_Activating(object sender, ActivatingEventArgs <object> e)
        {
            var key = GetKey(e.Component);

            _registrations.AddOrUpdate(key, 1, (k, value) => value + 1);
            _instances.GetOrAdd(key, e.Instance);
        }
示例#6
0
        protected static void CreateClassProxy(IInterceptor[] interceptors, ActivatingEventArgs <object> e, Type type, object instance,
                                               Type[] proxiedInterfaces)
        {
            // Ensure we don't try to proxy anything that can't be proxied
            if (type.IsSealed)
            {
                return;
            }

            var targetType = type;

            // Special handling for nested proxies...
            if (ProxyUtil.IsProxy(instance))
            {
                OverrideProxyInterceptors(interceptors, instance);
            }
            else
            {
                var proxyType = ProxyGenerator.ProxyBuilder.CreateClassProxyType(targetType, proxiedInterfaces,
                                                                                 ProxyGenerationOptions.Default);

                var activator = new ReflectionActivator(proxyType,
                                                        new DefaultConstructorFinder(),
                                                        new MostParametersConstructorSelector(),
                                                        GetConfiguredParams(ProxyGenerationOptions.Default, interceptors),
                                                        Enumerable.Empty <Parameter>());

                e.ReplaceInstance(activator.ActivateInstance(e.Context, e.Parameters));

                // Dispose of the old instance, if necessary
                var oldInstance = instance as IDisposable;
                oldInstance?.Dispose();
            }
        }
示例#7
0
        /// <summary>
        /// Registrations the activating.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Autofac.Core.ActivatingEventArgs&lt;System.Object&gt;"/> instance containing the event data.</param>
        private static void RegistrationActivating(object sender, ActivatingEventArgs<object> e)
        {
            // Ignore AspectConfiguration and IInterceptor types since they're being referenced via the Autofac
            // registration context. Otherwise calling e.Context.Resolve<IInterceptor> will fail when
            // the code below executes.
            if (e.Instance.GetType() == typeof (MasterProxy) || e.Instance is IInterceptor)
            {
                return;
            }

            var proxy = (MasterProxy)e.Context.Resolve(typeof(MasterProxy));

            if (!e.Instance.IsDecorated(proxy.Configuration))
            {
                return;
            }

            var pseudoList = new IInterceptor[proxy.Configuration.Interceptors.Count];
            pseudoList[0] = proxy;

            for (var i = 1; i < pseudoList.Length; i++)
            {
                pseudoList[i] = new PseudoInterceptor();
            }

            var interfaceTypes = e.Instance.GetType().GetInterfaces();
            var targetInterface =
                interfaceTypes.FirstMatch(proxy.Configuration.Namespaces);

            e.Instance = new ProxyGenerator().CreateInterfaceProxyWithTargetInterface(targetInterface, e.Instance, pseudoList);
        }
示例#8
0
 internal void OnScp914Activate(ActivatingEventArgs ev)
 {
     if (!config.Scp914.canBeActivatedGlobal && !config.Scp914.canBeActivated[ev.Player.Role])
     {
         ev.IsAllowed = false;
     }
 }
        private void OnActivating(object sender, ActivatingEventArgs<object> e)
        {
            if (e.Instance.GetType().IsArray)
            {
                return;
            }

            var serviceWithTypes = e.Component.Services.OfType<IServiceWithType>()
                                              .Select(x => x.ServiceType).ToList();
            if (!serviceWithTypes.Any())
            {
                return;
            }

            if (serviceWithTypes.Count == 1)
            {
                e.Instance = _proxyFactory.Create(e.Instance, serviceWithTypes.First(),
                                                                    new Type[] { });
            }
            else if (serviceWithTypes.All(x => x.IsInterface))
            {
                e.Instance = _proxyFactory.Create(e.Instance, e.Instance.GetType(),
                                                        serviceWithTypes.ToArray());
            }
            else
            {
                throw new NotSupportedException();
            }
        }
示例#10
0
 public void OnScp914Activation(ActivatingEventArgs ev)
 {
     tcp.SendData(new DataObjects.Events.Player
     {
         eventName = "Scp914Activation",
         player    = PlyToUser(ev.Player)
     });
 }
 private void RegistrationOnActivating(object sender, ActivatingEventArgs <object> activatingEventArgs)
 {
     this.depth--;
     Trace.Write(this.GetPrefix());
     Trace.Write("Activating ");
     Trace.Write(activatingEventArgs.Component.Activator.LimitType);
     Trace.WriteLine(string.Empty);
 }
示例#12
0
 private void RegistrationOnActivating(object sender, ActivatingEventArgs <object> activatingEventArgs)
 {
     Depth--;
     if (Logger.IsEnabled(LogEventLevel.Verbose))
     {
         Logger.Verbose($"{GetPrefix()}Resolving {{Type}}", activatingEventArgs.Component.Activator.LimitType);
     }
 }
示例#13
0
 private void RegistrationOnActivating(object sender, ActivatingEventArgs <object> activatingEventArgs)
 {
     _depth--;
     if (Log.IsVerboseEnabled())
     {
         Log.Verbose().WriteLine("{0}Activating {1}", GetPrefix(), activatingEventArgs.Component.Activator.LimitType);
     }
 }
    private void Registration_Activating(Object sender, ActivatingEventArgs <Object> e)
    {
        Object proxy = this._generator.CreateClassProxyWithTarget(
            e.Instance.GetType(),
            e.Instance,
            e.Context.Resolve <IEnumerable <IInterceptor> >().ToArray());

        e.ReplaceInstance(proxy);
    }
        private static void ComponentRegistration_Activating(object sender, ActivatingEventArgs <object> e)
        {
            if (e.Instance == null || e.Instance.IsProxy())
            {
                return;
            }
            if (!(e.Component.Activator is ReflectionActivator ||
                  e.Component.Activator is DelegateActivator ||
                  e.Component.Activator is InstanceActivator))
            {
                return;
            }
            var limitType = e.Instance.GetType();

            if (!limitType.GetTypeInfo().CanInherited())
            {
                return;
            }
            if (excepts.Any(x => limitType.Name.Matches(x)) || excepts.Any(x => limitType.Namespace.Matches(x)))
            {
                return;
            }
            var services = e.Component.Services.Select(x => ((IServiceWithType)x).ServiceType).ToList();

            if (!services.All(x => x.GetTypeInfo().CanInherited()) || services.All(x => x.GetTypeInfo().IsNonAspect()))
            {
                return;
            }
            var aspectValidator = new AspectValidatorBuilder(e.Context.Resolve <IAspectConfiguration>()).Build();

            if (services.All(x => !aspectValidator.Validate(x, true)) && !aspectValidator.Validate(limitType, false))
            {
                return;
            }
            var  proxyTypeGenerator = e.Context.Resolve <IProxyTypeGenerator>();
            Type proxyType; object instance;
            var  interfaceType = services.FirstOrDefault(x => x.GetTypeInfo().IsInterface);

            if (interfaceType == null)
            {
                var baseType = services.FirstOrDefault(x => x.GetTypeInfo().IsClass) ?? limitType;
                proxyType = proxyTypeGenerator.CreateClassProxyType(baseType, limitType);
                var activator = new ReflectionActivator(proxyType, new DefaultConstructorFinder(type => type.GetTypeInfo().DeclaredConstructors.ToArray()), new MostParametersConstructorSelector(), new AParameter[0], new AParameter[0]);
                instance = activator.ActivateInstance(e.Context, e.Parameters);
            }
            else
            {
                proxyType = proxyTypeGenerator.CreateInterfaceProxyType(interfaceType, limitType);
                instance  = Activator.CreateInstance(proxyType, new object[] { e.Context.Resolve <IAspectActivatorFactory>(), e.Instance });
            }

            var propertyInjector = e.Context.Resolve <IPropertyInjectorFactory>().Create(instance.GetType());

            propertyInjector.Invoke(instance);
            e.Instance = instance;
            e.Component.RaiseActivating(e.Context, e.Parameters, ref instance);
        }
        private void OnComponentActivating(object sender, ActivatingEventArgs <object> e)
        {
            var originalInstance = e.Instance;
            var newInstance      = _interceptor.OnResolving(originalInstance, e.Context);

            if (newInstance != originalInstance)
            {
                e.ReplaceInstance(newInstance);
            }
        }
示例#17
0
        /// <summary>
        /// Called by the container once an instance has been constructed.
        /// </summary>
        /// <param name="service">Service which is activating</param>
        /// <param name="context">The context in which the instance was activated.</param>
        /// <param name="parameters">The parameters supplied to the activator.</param>
        /// <param name="instance">The instance.</param>
        public void RaiseActivating(Service service, IComponentContext context, IEnumerable <Parameter> parameters, ref object instance)
        {
            var ev = Activating;

            if (ev != null)
            {
                var args = new ActivatingEventArgs <object>(service, context, this, parameters, instance);
                ev(this, args);
                instance = args.Instance;
            }
        }
 public void On914Activate(ActivatingEventArgs ev)
 {
     try
     {
         ResetAFKTime(ev.Player);
     }
     catch (Exception e)
     {
         Log.Error($"ERROR In On914Activate(): {e}");
     }
 }
示例#19
0
        public void RaiseActivating(IComponentContext context, IEnumerable <Parameter> parameters, ref object instance)
        {
            EventHandler <ActivatingEventArgs <object> > activating = this.Activating;

            if (activating != null)
            {
                ActivatingEventArgs <object> e = new ActivatingEventArgs <object>(context, this, parameters, instance);
                activating(this, e);
                instance = e.Instance;
            }
        }
示例#20
0
        private static async void ProcessOnInit(object sender, ActivatingEventArgs <object> e)
        {
            if (e.Instance is IOnInit)
            {
                (e.Instance as IOnInit).OnInit();
            }

            if (e.Instance is IOnInitAsync)
            {
                await(e.Instance as IOnInitAsync).OnInitAsync().ConfigureAwait(true);
            }
        }
 public IRegistrationBuilder <TLimit, TActivatorData, TRegistrationStyle> OnActivating(Action <IActivatingEventArgs <TLimit> > handler)
 {
     if (handler == null)
     {
         throw new ArgumentNullException("handler");
     }
     this.RegistrationData.ActivatingHandlers.Add(delegate(object s, ActivatingEventArgs <object> e) {
         ActivatingEventArgs <TLimit> args = new ActivatingEventArgs <TLimit>(e.Context, e.Component, e.Parameters, (TLimit)e.Instance);
         handler(args);
         e.Instance = args.Instance;
     });
     return(this);
 }
示例#22
0
        private void Registration_Activating(object sender, ActivatingEventArgs <object> e)
        {
            IComponentRegistration registration = sender as IComponentRegistration;
            Type serviceType = registration.Metadata["ServiceType"] as Type;
            ComponentCreatingEventArgs moduleComponentCreatingEventArgs =
                new ComponentCreatingEventArgs(new ComponentContextComponentManager(e.Context), serviceType, e.Instance);

            Debug.WriteLine($"[{registration.Id}] ComponentCreating : {moduleComponentCreatingEventArgs}");
            this.ComponentCreating?.Invoke(this, moduleComponentCreatingEventArgs);
            if (moduleComponentCreatingEventArgs.IsReplaced)
            {
                e.Instance = moduleComponentCreatingEventArgs.ReplacedObject;
            }
        }
示例#23
0
        /// <summary>
        /// Called by the container once an instance has been constructed.
        /// </summary>
        /// <param name="context">The context in which the instance was activated.</param>
        /// <param name="parameters">The parameters supplied to the activator.</param>
        /// <param name="instance">The instance.</param>
        public void RaiseActivating(IComponentContext context, IEnumerable <Parameter> parameters, ref object instance)
        {
            var handler = Activating;

            if (handler == null)
            {
                return;
            }

            var args = new ActivatingEventArgs <object>(context, this, parameters, instance);

            handler(this, args);
            instance = args.Instance;
        }
示例#24
0
        private void ComponentRegistration_Activating(object sender, ActivatingEventArgs <object> e)
        {
            IComponentRegistration     registration = sender as IComponentRegistration;
            ComponentCreatingEventArgs moduleComponentCreatingEventArgs =
                new ComponentCreatingEventArgs(new ComponentContextComponentManager(e.Context), serviceType, e.Instance);

            Debug.WriteLine($"[{registration.Id}] ComponentCreating : {moduleComponentCreatingEventArgs}");
            this.ComponentCreating?.Invoke(this, moduleComponentCreatingEventArgs);
            if (moduleComponentCreatingEventArgs.IsReplaced)
            {
                Debug.WriteLine($"[{registration.Id}] ComponentReplaced : {moduleComponentCreatingEventArgs.ReplacedObject.GetType()} : {moduleComponentCreatingEventArgs.RequiredType}");
                e.Instance = moduleComponentCreatingEventArgs.ReplacedObject;
            }
        }
示例#25
0
        private static bool Prefix(Scp914Controller __instance, ReferenceHub ply, byte colliderId)
        {
            if (__instance._remainingCooldown > 0.0)
            {
                return(false);
            }
            switch ((Scp914InteractCode)colliderId)
            {
            case Scp914InteractCode.ChangeMode:
                Scp914KnobSetting scp914KnobSetting;
                if (__instance._knobSetting + 1 > Scp914KnobSetting.VeryFine)
                {
                    scp914KnobSetting = Scp914KnobSetting.Rough;
                }
                else
                {
                    scp914KnobSetting = __instance._knobSetting + 1;
                }
                ChangingKnobSettingEventArgs ev = new ChangingKnobSettingEventArgs(Player.Get(ply), scp914KnobSetting);

                Handlers.Scp914.OnChangingKnobSetting(ev);
                if (!ev.IsAllowed)
                {
                    return(false);
                }

                __instance._remainingCooldown  = __instance._knobChangeCooldown;
                scp914KnobSetting              = ev.KnobSetting;
                __instance.Network_knobSetting = scp914KnobSetting;
                __instance.RpcPlaySound(0);
                break;

            case Scp914InteractCode.Activate:
                ActivatingEventArgs ev2 = new ActivatingEventArgs(Player.Get(ply));

                Handlers.Scp914.OnActivating(ev2);

                if (!ev2.IsAllowed)
                {
                    return(false);
                }
                __instance._remainingCooldown    = __instance._totalSequenceTime;
                __instance._isUpgrading          = true;
                __instance._itemsAlreadyUpgraded = false;
                __instance.RpcPlaySound(1);
                break;
            }

            return(false);
        }
        /// <summary>
        /// Add a handler for the Activating event.
        /// </summary>
        /// <param name="handler">The event handler.</param>
        /// <returns>A registration builder allowing further configuration of the component.</returns>
        public IRegistrationBuilder <TLimit, TActivatorData, TRegistrationStyle> OnActivating(Action <IActivatingEventArgs <TLimit> > handler)
        {
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }

            RegistrationData.ActivatingHandlers.Add((s, e) =>
            {
                var args = new ActivatingEventArgs <TLimit>(e.Context, e.Component, e.Parameters, (TLimit)e.Instance);
                handler(args);
                e.Instance = args.Instance;
            });
            return(this);
        }
示例#27
0
        internal void Activating(ActivatingEventArgs ev)
        {
            if (Plugin.Instance.Config.Activating == "")
            {
                return;
            }
            string message = Plugin.Instance.Config.Activating.Replace("%player%", ev.Player.ToString());


            if (Plugin.Instance.Config.debug_to_console)
            {
                Log.Debug(message: "[ " + Plugin.Instance.Config.scp914_name + "] " + message);
            }
            Plugin.sendWebHook(Plugin.Instance.Config.scp914_url, message, Plugin.Instance.Config.scp914_name);
        }
示例#28
0
        private static void ActivatingComponent(object sender, ActivatingEventArgs <object> e)
        {
            var type      = e.Instance.GetType();
            var isFromMef = (e.Component.Metadata.ContainsKey("Source") &&
                             e.Component.Metadata["Source"] as string == "MEF");
            var isNotComposable = type.GetCustomAttributes(typeof(PartNotComposableAttribute), false).Any();

            if (isNotComposable || isFromMef)
            {
                return;
            }

            var container = e.Context.ResolveNamed <CompositionContainer>(AutofacCompositionContainerName);

            container.SatisfyImportsOnce(e.Instance);
        }
示例#29
0
        protected virtual void InterceptActivation(IInterceptor[] interceptors, ActivatingEventArgs <object> e, HashSet <Type> proxyTypes)
        {
            var type = e.Instance.GetType();
            var componentServices = e.Component.Services.OfType <IServiceWithType>().ToArray();

            Predicate <Type> isExplicitlyIncludedType = t => IncludeTypes.Any() && !IncludeTypes.Contains(t);
            Predicate <IEnumerable <IServiceWithType> > allServicesAreIncludedInNamespaces = services =>
                                                                                             services.All(swt => IncludeNamespaces.Any(ns => swt.ServiceType.IsInNamespace(ns)));

            // Short circuit if any service type is explicitly registered via 'includeNamespaces' or 'includeTypes'
            if (!isExplicitlyIncludedType(type) &&
                (!allServicesAreIncludedInNamespaces(componentServices) ||
                 componentServices                           // Only proxy classes/INTERFACES that are VISIBLE
                 .All(swt => !swt.ServiceType.IsVisible)))
            {
                return;
            }

            // prevent proxying the known proxies; doesn't handle other proxies
            if (proxyTypes.Contains(type) ||
                componentServices.Any(swt => ExcludeTypes.Contains(swt.ServiceType.FullName) ||
                                      ExcludeNamespaces.Any(ns => swt.ServiceType.IsInNamespace(ns))) ||
                ExcludeAssemblies.Contains(type.Assembly.GetName().Name) ||
                type.IsAssignableTo <IEnumerable>())                   // prevent IEnumerable/Collection proxies
            {
                return;
            }

            var proxiedInterfaces =
                type.GetInterfaces()
                .Where(i => i.IsVisible && !i.FullName.Equals(ReservedProxyInterface))
                .ToArray();
            var instance = e.Instance;

            var context = new InterceptionContext
            {
                Interceptors        = interceptors,
                EventArgs           = e,
                ComponentServices   = componentServices,
                ProxyableInterfaces = proxiedInterfaces,
                ExistingInstance    = instance,
                InstanceType        = type
            };

            ExecuteProxyStrategy(context);
        }
        private void Activating(object sender, ActivatingEventArgs<object> e)
        {
            var vmType = e.Instance.GetType();

            if (!vmType.FullName.EndsWith("ViewModel"))
                return;

            // Convention to find attachments from a ViewModel
            // This can be done better.
            var attachmentType = Type.GetType(vmType.FullName.Replace("ViewModel", "Attachment"));

            if (attachmentType == null || !e.Context.IsRegistered(attachmentType))
                return;

            var attachment = (IAttachment)e.Context.Resolve(attachmentType);

            attachment.AttachTo(e.Instance);
        }
        private void Activating(object sender, ActivatingEventArgs <object> e)
        {
            var vmType = e.Instance.GetType();

            if (!vmType.Name.EndsWith("ViewModel"))
            {
                return;
            }

            var attachments = Conventions.FindAll <AttachmentConventions>(vmType)
                              .Where(t => e.Context.IsRegistered(t))
                              .Select(t => (IAttachment)e.Context.Resolve(t));

            foreach (var a in attachments)
            {
                a.AttachTo(e.Instance);
            }
        }
示例#32
0
        private void Compose(Type target, Type[] services, ActivatingEventArgs <object> aea)
        {
            if (HasCreationTypes)
            {
                var allCreationTypes = new HashSet <Type>(AllCreationTypes);
                ProcessAfterConstruction(aea.Instance, allCreationTypes, services);
            }
            if (!target.IsInterface || !HasRulesTypes && !HasMethodTypes)
            {
                return;
            }
            var intercepted = SatisfiesRule(services);

            if (intercepted.Length > 0)
            {
                aea.Instance = CreateInterfaceProxy(target, aea.Instance, services.ToArray(), intercepted);
            }
        }
示例#33
0
            public Node Activating(ActivatingEventArgs <object> e)
            {
                // move focus up a level on the tree
                if (_component == null)
                {
                    TraceMessage("UNMATCHED: Activating[{2}] {0} {1}", e.Component);
                    return(this);
                }

                if (_component.Id != e.Component.Id)
                {
                    TraceMessage("MISSING: Activating[{2}] {0} {1}", _component);
                    return(_parent.Activating(e));
                }

                TraceMessage("Activating[{2}] {0} {1}", e.Component);
                Interlocked.Increment(ref _activatingCount);
                return(_parent);
            }
示例#34
0
        /// <summary>
        /// Registrations the activating.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Autofac.Core.ActivatingEventArgs&lt;System.Object&gt;"/> instance containing the event data.</param>
        private static void RegistrationActivating(object sender, ActivatingEventArgs<object> e)
        {
            // Ignore AspectConfiguration and IInterceptor types since they're being referenced via the Autofac
            // registration context. Otherwise calling e.Context.Resolve<IInterceptor> will fail when
            // the code below executes.

            if(e.Instance is MasterProxy)
            {
                // for master proxy we need to assign reference to current container, which is used to resolve aspects from
                // AutofacServiceLocatorAdapter cannot be built just with e.Context despite fact that e.Context is of IComponentContext
                // e.Context is valid only in scope of current instance activation
                // To get valid IComponentContext we need to resolve it in the following way
                ((MasterProxy) e.Instance).Container = new AutofacServiceLocatorAdapter(e.Context.Resolve<IComponentContext>());
                return;
            }

            // inteceptors could not be intercepted too, thus skip the code below
            if (e.Instance is IInterceptor)
            {
                return;
            }

            var proxy = (MasterProxy)e.Context.Resolve(typeof(MasterProxy));

            if (!e.Instance.IsDecorated(proxy.Configuration))
            {
                return;
            }

            var pseudoList = new IInterceptor[proxy.Configuration.Interceptors.Count];
            pseudoList[0] = proxy;

            for (var i = 1; i < pseudoList.Length; i++)
            {
                pseudoList[i] = new PseudoInterceptor();
            }

            var targetInterface = e.Instance.GetType().GetTypeToDynamicProxy(proxy.Configuration.Namespaces);

            e.Instance = AspectUtility.CreateProxy(targetInterface, e.Instance, pseudoList);
        }
示例#35
0
        /// <summary>
        /// 获取可释放对象列表
        /// </summary>
        /// <param name="lifetimeScope">范围容器</param>
        /// <returns>可释放对象列表</returns>
        private static IList <IDisposable> GetDisposableInstances(ILifetimeScope lifetimeScope)
        {
            #region # 验证

            if (lifetimeScope == null)
            {
                return(new List <IDisposable>());
            }

            #endregion

            IList <IDisposable> disposables = new List <IDisposable>();
            Type lifetimeScopeType          = lifetimeScope.GetType();

            const string disposerPropertyName     = "Disposer";
            const string disposableItemsFieldName = "_items";
            PropertyInfo disposerProperty         = lifetimeScopeType.GetProperty(disposerPropertyName, BindingFlags.Public | BindingFlags.Instance);
            object       disposer             = disposerProperty.GetValue(lifetimeScope, null);
            Type         disposerType         = disposer.GetType();
            FieldInfo    disposableItemsField = disposerType.GetField(disposableItemsFieldName, BindingFlags.NonPublic | BindingFlags.Instance);
            object       disposableItems      = disposableItemsField?.GetValue(disposer);
            if (disposableItems is Stack <IDisposable> stack)
            {
                foreach (IDisposable disposable in stack)
                {
                    Type releaseActionType = disposable.GetType();

                    const string actionFieldName           = "_action";
                    const string eventArgsFieldName        = "e";
                    FieldInfo    actionField               = releaseActionType.GetField(actionFieldName, BindingFlags.NonPublic | BindingFlags.Instance);
                    Action       action                    = (Action)actionField.GetValue(disposable);
                    Type         targetType                = action.Target.GetType();
                    FieldInfo    eventArgsField            = targetType.GetField(eventArgsFieldName, BindingFlags.Public | BindingFlags.Instance);
                    ActivatingEventArgs <object> eventArgs = (ActivatingEventArgs <object>)eventArgsField.GetValue(action.Target);

                    disposables.Add((IDisposable)eventArgs.Instance);
                }
            }

            return(disposables);
        }
示例#36
0
        private void RegistrationActivating(object sender, ActivatingEventArgs <object> e)
        {
            var interceptorProxy = e.Instance as IInterceptorProxy;

            if (interceptorProxy != null)
            {
                interceptorProxy.Container = new ServiceLocatorAdapter(e.Context.Resolve <IComponentContext>());
                return;
            }

            if (e.Instance is IInterceptor)
            {
                return;
            }

            if (InterceptorHelper.HasInterceptor(e.Instance.GetType()))
            {
                var proxy = e.Context.Resolve <IInterceptorProxy>();
                e.Instance = _proxyFactory.CreateProxy(e.Instance, proxy);
            }
        }
        /// <summary>
        /// Called by the container once an instance has been constructed.
        /// </summary>
        /// <param name="context">The context in which the instance was activated.</param>
        /// <param name="parameters">The parameters supplied to the activator.</param>
        /// <param name="instance">The instance.</param>
        public void RaiseActivating(IComponentContext context, IEnumerable<Parameter> parameters, ref object instance)
        {
            var handler = Activating;
            if (handler == null) return;

            var args = new ActivatingEventArgs<object>(context, this, parameters, instance);
            handler(this, args);
            instance = args.Instance;
        }
 protected virtual void OnComponentActivating(object sender, ActivatingEventArgs<object> e)
 {
 }
		private void RegistrationOnActivating(object sender, ActivatingEventArgs<object> activatingEventArgs)
		{
			depth--;    
			Debug.WriteLine("{0}Activating {1}", GetPrefix(), activatingEventArgs.Component.Activator.LimitType);
		}
示例#40
0
		/// <summary>
		/// Called by the container once an instance has been constructed.
		/// </summary>
		/// <param name="service">Service which is activating</param>
		/// <param name="context">The context in which the instance was activated.</param>
		/// <param name="parameters">The parameters supplied to the activator.</param>
		/// <param name="instance">The instance.</param>
		public void RaiseActivating(Service service, IComponentContext context, IEnumerable<Parameter> parameters, ref object instance)
		{
			var ev = Activating;
			if (ev != null)
			{
				var args = new ActivatingEventArgs<object>(service, context, this, parameters, instance);
				ev(this, args);
				instance = args.Instance;
			}
		}
        private static void ActivatingComponent(object sender, ActivatingEventArgs<object> e)
        {
            var type = e.Instance.GetType();
            var isFromMef = (e.Component.Metadata.ContainsKey("Source") &&
                             e.Component.Metadata["Source"] as string == "MEF");
            var isNotComposable = type.GetCustomAttributes(typeof (PartNotComposableAttribute), false).Any();
            if (isNotComposable || isFromMef) return;

            var container = e.Context.ResolveNamed<CompositionContainer>(AutofacCompositionContainerName);
            container.SatisfyImportsOnce(e.Instance);
        }
示例#42
0
 private static void Activating(ThreadContext context, ActivatingEventArgs<object> activating) {
     context.Focus = context.Focus.Activating(activating);
 }
示例#43
0
            public Node Activating(ActivatingEventArgs<object> e) {
                // move focus up a level on the tree
                if (_component == null) {
                    TraceMessage("UNMATCHED: Activating[{2}] {0} {1}", e.Component);
                    return this;
                }

                if (_component.Id != e.Component.Id) {
                    TraceMessage("MISSING: Activating[{2}] {0} {1}", _component);
                    return _parent.Activating(e);
                }

                TraceMessage("Activating[{2}] {0} {1}", e.Component);
                Interlocked.Increment(ref _activatingCount);
                return _parent;
            }
示例#44
0
 private void Registration_Activating(object sender, ActivatingEventArgs<object> e)
 {
     var key = GetKey(e.Component);
     _registrations.AddOrUpdate(key, 1, (k, value) => value + 1);
     _instances.GetOrAdd(key, e.Instance);
 }