Exemplo n.º 1
0
        private static IEnumerable <PropertyInjector> CreatePropertyInjectors(ScopedComponentBase instance)
        {
            Type componentType = instance.GetType();

            var properties = componentType
                             .GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                             .Select(p => new { Property = p, Attribute = p.GetCustomAttribute <InjectScopedAttribute>() })
                             .Where(x => x.Attribute != null)
                             .Select(x => new { x.Property.PropertyType, x.Property.SetMethod })
                             .Where(x => x.SetMethod != null);

            var injectors = new List <PropertyInjector>();

            foreach (var property in properties)
            {
                var setterDelegateType = typeof(Action <,>).MakeGenericType(componentType, property.PropertyType);
                var setterDelegate     = Delegate.CreateDelegate(setterDelegateType, property.SetMethod);

                Action <object, object> setProperty = (inst, service) => setterDelegate.DynamicInvoke(inst, service);

                var injector = new PropertyInjector(property.PropertyType, setProperty);
                injectors.Add(injector);
            }
            return(injectors);
        }
Exemplo n.º 2
0
        public static void InjectDependencies(ScopedComponentBase instance, IServiceProvider serviceProvider)
        {
            IEnumerable <PropertyInjector> propertyInjectors = TypeToPropertyInjectors.GetOrAdd(instance.GetType(), _ => CreatePropertyInjectors(instance));

            var serviceTypes = propertyInjectors.Select(x => x.ServiceType).Distinct().ToDictionary(x => x, x => serviceProvider.GetService(x));

            foreach (var injector in propertyInjectors)
            {
                injector.PropertySetter(instance, serviceTypes[injector.ServiceType]);
            }
        }