private LinkedList <DelegateServiceDefintion> CacheDelegate(DelegateServiceDefintion defintion)
        {
            var list = cache.GetOrAdd(defintion.ServiceType, i => new LinkedList <DelegateServiceDefintion>());

            list.Add(defintionHandler.Handle(defintion));
            return(list);
        }
Example #2
0
        public DelegateServiceDefintion Handle(DelegateServiceDefintion defintion)
        {
            var properties = defintion.ImplementationType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                             .Where(i => i.CanWrite && i.GetReflector().IsDefined <FromDIAttribute>())
                             .ToArray();

            if (properties.Length == 0)
            {
                return(defintion);
            }
            else
            {
                return(new DelegateServiceDefintion(defintion.ServiceType, defintion.ImplementationType,
                                                    defintion.Lifetime, CreatePropertyInjector(properties, defintion.ImplementationFactory), defintion.Name));
            }
        }
        private LinkedList <DelegateServiceDefintion> TypeToDelegateServiceDefintion(TypeServiceDefintion typeServiceDefintion)
        {
            var serviceType        = typeServiceDefintion.ServiceType;
            var implementationType = typeServiceDefintion.ImplementationType;
            var constructor        = implementationType.GetConstructors().FirstOrDefault(i => i.IsPublic);

            if (constructor == null)
            {
                throw new NotSupportedException($"DependencyInjection not supported no public constructor of {implementationType}.");
            }
            var reflector = constructor.GetReflector();
            Func <INamedServiceProvider, object> func = null;
            var parameters = reflector.Parameters
                             .Select(i => Tuple.Create(i.Member.ParameterType, i.GetCustomAttribute <FromDIAttribute>()?.Named))
                             .ToArray();
            var ctor = reflector.Invoke;

            if (parameters.Length > 0)
            {
                func = i =>
                {
                    var args = new object[parameters.Length];
                    for (int j = 0; j < parameters.Length; j++)
                    {
                        var p = parameters[j];
                        args[j] = i.GetService(p.Item1, p.Item2);
                    }
                    return(ctor(args));
                };
            }
            else
            {
                var args = new object[0];
                func = i => ctor(args);
            }
            var defintion = new DelegateServiceDefintion(serviceType, implementationType, typeServiceDefintion.Lifetime, func, typeServiceDefintion.Name);

            return(CacheDelegate(defintion));
        }