コード例 #1
0
        public static object CreateInstance(RegisteredComponent registeredComponent, IContainer container)
        {
            var componentType = registeredComponent.GetComponentType();

            if ((componentType.IsInterface) || (componentType.IsAbstract))
            {
                throw new InvalidOperationException($"Type {componentType} cannot have instance");
            }

            var method      = typeof(Container).GetMethod("Contains");
            var constructor = componentType
                              .GetConstructors()
                              .Where(constr => constr
                                     .GetParameters()
                                     .Where(param => (bool)method
                                            .MakeGenericMethod(param.ParameterType)
                                            .Invoke(container, null))
                                     == null)
                              .FirstOrDefault();

            if (constructor == null)
            {
                throw new Exception("Нет такоого конструктора");
            }

            return(Activator.CreateInstance(componentType, ResolveArguments(constructor, container)));
        }
コード例 #2
0
ファイル: Container.cs プロジェクト: LaserKoala/DIContainer
        // private bool IsBuilded = false;


        public IRegisteredComponent RegisterType <TComponent>()
        {
            var componentType       = typeof(TComponent);
            var registeredComponent = registeredComponents
                                      .Where(regComponent => regComponent.GetComponentType() == componentType)
                                      .FirstOrDefault();

            if (registeredComponent != null)
            {
                return(registeredComponent);
            }
            var newComponent = new RegisteredComponent(componentType);

            registeredComponents.Add(newComponent);

            return(newComponent);
        }