예제 #1
0
        /// <summary>
        /// Builds all nodes due the retrieved nodes data from the Circuit File.
        /// </summary>
        /// <param name="parsedNodes">A list containing all data of the retrieved nodes from the Circuit file.</param>
        /// <param name="cbnv">The visitor used to bind the circuit nodes.</param>
        /// <returns>A dictionary containing all built nodes out of the retrieved nodes data from the Circuit file.</returns>
        private static Dictionary <string, Node> BuildNodes(IEnumerable <string> parsedNodes, CircuitBindNodeVisitor cbnv)
        {
            const string METHOD_TAG = "BuildNodes";

            var  nodes = new Dictionary <string, Node>();
            Node node  = null;

            try
            {
                foreach (var parsedNode in parsedNodes)
                {
                    node = FactoryMethod <string, Node> .create(parsedNode.Split(':')[1]);

                    node.accept(cbnv);
                    nodes.Add(parsedNode.Split(':')[0].ToLower(), node);
                }
            }
            catch (Exception)
            {
                if (node != null)
                {
                    throw new CurrentNodeNotFoundException(CLASS_TAG, METHOD_TAG,
                                                           "Unexpected value for node '" + node.GetType() + "' received.");
                }

                Console.WriteLine(@"Unexpected value for node found!");
            }

            return(nodes);
        }
 private FactoryMethodSelector SelectMostResolvableConstructor(bool includeNonPublic = false)
 {
     return(request =>
     {
         var implementationType = request.ImplementationType.ThrowIfNull();
         var ctors = implementationType.GetAllConstructors(includeNonPublic: true).ToArrayOrSelf();
         if (ctors.Length == 0)
         {
             return null;         // Delegate handling of constructor absence to the Caller code.
         }
         if (ctors.Length == 1)
         {
             return FactoryMethod.Of(ctors[0]);
         }
         var ctorsWithMoreParamsFirst = ctors
                                        .Select(c => new { Ctor = c, Params = c.GetParameters() })
                                        .OrderByDescending(x => x.Params.Length);
         var rules = request.Container.Rules;
         var parameterSelector = rules.Parameters.And(request.Made.Parameters)(request);
         var matchedCtor = ctorsWithMoreParamsFirst.FirstOrDefault(x =>
                                                                   x.Params.All(p => IsResolvableParameter(p, parameterSelector, request)));
         var ctor = matchedCtor.ThrowIfNull(Error.UnableToFindCtorWithAllResolvableArgs, request).Ctor;
         return FactoryMethod.Of(ctor);
     });
 }
예제 #3
0
        static ContainerBuilder()
        {
            var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "appget.*", SearchOption.TopDirectoryOnly).Where(c => c.EndsWith(".exe") || c.EndsWith(".dll"));

            var ass = files.Select(Assembly.LoadFile).ToList();

            AssemblyTypes = ass.SelectMany(c => c.ExportedTypes
                                           .Where(t => !t.IsAbstract && !t.IsInterface && !t.IsEnum && t.Namespace != null && t.Namespace.StartsWith("AppGet.")))
                            .ToList();

            var rules = Rules.Default
                        .WithAutoConcreteTypeResolution()
                        .WithDefaultReuse(Reuse.Singleton)
                        .WithDefaultIfAlreadyRegistered(IfAlreadyRegistered.AppendNotKeyed);


            var made = FactoryMethod.Constructor(mostResolvable: true);

            Container = new Container(rules);

            Container.RegisterMany(ass, ShouldRegisterAs, made: made);

            RegisterLoggerFactory();

            RegisterTransienttInstallers(made);

            RegisterHandlers <ICommandHandler>();

            Container.Resolve <IHub>().Publish(new ApplicationStartedEvent());
        }
예제 #4
0
		/*----------------------------------------------------------------------------------------*/
		#region Public Methods
		/// <summary>
		/// Creates a new instance of a type by calling the injector's constructor.
		/// </summary>
		/// <param name="arguments">The arguments to pass to the constructor.</param>
		/// <returns>A new instance of the type associated with the injector.</returns>
		public object Invoke(params object[] arguments)
		{
			if (_factoryMethod == null)
				_factoryMethod = DynamicMethodFactory.CreateFactoryMethod(Member);

			return _factoryMethod.Invoke(arguments);
		}
예제 #5
0
        public void DentistCreationWithoutReflectionTest()
        {
            FactoryMethod factory = DoctorFactory.GetFactory();
            IPerson       x       = factory.GetPersonWithoutReflection(typeof(Pneumologist));

            Assert.AreSame(x.GetType(), typeof(Pneumologist));
        }
    public void Run()
    {
        ICharacter player;

        player = FactoryMethod.Choose(CharacterEnum.Luigi);
        player.choosed();
    }
예제 #7
0
 public static void RemoveFactory <T>(string tag, FactoryMethod method)
 {
     foreach (var key in constructors.Keys.FindAll <FactoryKey>(k => k.type == typeof(T) && k.tag == tag))
     {
         constructors.Remove(key);
     }
 }
예제 #8
0
        private static void RegisterFactoryMethods(IRegistrator registrator, ExportedRegistrationInfo factoryInfo)
        {
            // NOTE: Cast is required for NET35
            var members = factoryInfo.ImplementationType.GetAll(t =>
                                                                t.DeclaredMethods.Cast <MemberInfo>().Concat(
                                                                    t.DeclaredProperties.Cast <MemberInfo>().Concat(
                                                                        t.DeclaredFields.Cast <MemberInfo>())));

            foreach (var member in members)
            {
                var attributes = member.GetAttributes().ToArrayOrSelf();
                if (!IsExportDefined(attributes))
                {
                    continue;
                }

                var memberReturnType = member.GetReturnTypeOrDefault();
                var registrationInfo = GetRegistrationInfoOrDefault(memberReturnType, attributes).ThrowIfNull();

                var factoryExport      = factoryInfo.Exports[0];
                var factoryServiceInfo = member.IsStatic() ? null :
                                         ServiceInfo.Of(factoryExport.ServiceType, IfUnresolved.ReturnDefault, factoryExport.ServiceKeyInfo.Key);

                var factoryMethod = FactoryMethod.Of(member, factoryServiceInfo);
                var factory       = registrationInfo.CreateFactory(Made.Of(_ => factoryMethod));

                var serviceExports = registrationInfo.Exports;
                for (var i = 0; i < serviceExports.Length; i++)
                {
                    var export = serviceExports[i];
                    registrator.Register(factory,
                                         export.ServiceType, export.ServiceKeyInfo.Key, IfAlreadyRegistered.AppendNotKeyed, false);
                }
            }
        }
예제 #9
0
 public void SetFactoryMethod(FactoryMethod <TKey, TValue> _factory)
 {
     if (_factory != null)
     {
         factory = _factory;
     }
 }
예제 #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DelegateTarget" /> class.
        /// </summary>
        /// <param name="factory">Required - the factory delegate.  Must have a return type and can take
        /// 0 or more parameters.</param>
        /// <param name="declaredType">Optional - type that will be set into the <see cref="DeclaredType" /> for the target;
        /// if not provided, then it will be derived from the <paramref name="factory" />'s return type</param>
        /// <param name="scopeBehaviour">Scope behaviour for this delegate.  The default is <see cref="ScopeBehaviour.Implicit"/>, which means
        /// that that any returned instance will be tracked implicitly by the active scope.  If the delegate produces a new instance, then
        /// this or <see cref="ScopeBehaviour.Explicit"/> can be used safely - the choice being whether
        /// the expression should produce one instance per scope, or should act as a disposable transient object.</param>
        /// <param name="scopePreference">If <paramref name="scopeBehaviour"/> is not <see cref="ScopeBehaviour.None"/>, then this controls
        /// the preferred scope for the instance to be tracked.  Defaults to <see cref="ScopePreference.Current"/></param>
        /// <exception cref="ArgumentException">If the <paramref name="factory" /> represents a void delegate or if
        /// <paramref name="declaredType" /> is passed but the type is not compatible with the return type of
        /// <paramref name="factory" />.</exception>
        /// <exception cref="ArgumentNullException">If <paramref name="factory" /> is null</exception>
        public DelegateTarget(
            Delegate factory,
            Type declaredType               = null,
            ScopeBehaviour scopeBehaviour   = ScopeBehaviour.Implicit,
            ScopePreference scopePreference = ScopePreference.Current)
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            FactoryMethod = factory.GetMethodInfo();

            if (FactoryMethod.ReturnType == typeof(void))
            {
                throw new ArgumentException("Factory must have a return type", nameof(factory));
            }
            if (FactoryMethod.GetParameters().Any(p => p.ParameterType.IsByRef))
            {
                throw new ArgumentException("Delegates which have ref or out parameters are not permitted as the factory argument", nameof(factory));
            }

            if (declaredType != null)
            {
                if (!TypeHelpers.AreCompatible(FactoryMethod.ReturnType, declaredType) && !TypeHelpers.AreCompatible(declaredType, FactoryMethod.ReturnType))
                {
                    throw new ArgumentException(string.Format(ExceptionResources.DeclaredTypeIsNotCompatible_Format, declaredType, FactoryMethod.ReturnType), nameof(declaredType));
                }
            }

            this._declaredType    = declaredType;
            this._scopeBehaviour  = scopeBehaviour;
            this._scopePreference = scopePreference;
            Factory = factory;
        }
예제 #11
0
        public void GermanTeacherCreationWithoutReflectionTest()
        {
            FactoryMethod factory = TeacherFactory.GetFactory();
            IPerson       x       = factory.GetPersonWithoutReflection(typeof(GermanTeacher));

            Assert.AreSame(x.GetType(), typeof(GermanTeacher));
        }
예제 #12
0
        public void CompareFormatterServicesActivationAndDynamicFactoryMethod()
        {
            int iterations = 1000000;

            Stopwatch stopwatch1 = new Stopwatch();
            Stopwatch stopwatch2 = new Stopwatch();

            ConstructorInfo constructor   = typeof(BenchmarkObject).GetConstructor(new Type[] { typeof(int), typeof(string) });
            FactoryMethod   factoryMethod = DynamicMethodFactory.CreateFactoryMethod(constructor);

            for (int index = 0; index < iterations; index++)
            {
                stopwatch1.Start();
                BenchmarkObject mock1 = (BenchmarkObject)FormatterServices.GetSafeUninitializedObject(typeof(BenchmarkObject));
                constructor.Invoke(mock1, new object[] { 42, "foobar" });
                stopwatch1.Stop();

                stopwatch2.Start();
                BenchmarkObject mock2 = (BenchmarkObject)factoryMethod(42, "foobar");
                stopwatch2.Stop();
            }

            Console.WriteLine("{0:0,0} iterations:", iterations);
            Console.WriteLine("FormatterServices/Constructor.Invoke: {0:0,0} ms", stopwatch1.ElapsedMilliseconds);
            Console.WriteLine("Dynamic FactoryMethod: {0:0,0} ms", stopwatch2.ElapsedMilliseconds);
            Console.WriteLine("Speedup: {0:f}x",
                              ((double)stopwatch1.ElapsedMilliseconds / (double)stopwatch2.ElapsedMilliseconds));
        }
 public void SetFactoryMethod(FactoryMethod <T> _factory)
 {
     if (_factory != null)
     {
         factory = _factory;
     }
 }
예제 #14
0
파일: HttpFactory.cs 프로젝트: wingcd/utnt
        /// <summary>
        /// Create a type.
        /// </summary>
        /// <typeparam name="T">Type to create</typeparam>
        /// <returns>Created type.</returns>
        public T Get <T>(params object[] constructorArguments) where T : class
        {
            Type          type   = typeof(T);
            FactoryMethod method = FindFactoryMethod(type);

            if (method == null)
            {
                _logger.Error("No factory method is associated with '" + type.FullName + "'.");
                return(null);
            }

            object createdType = method(type, constructorArguments);

            if (createdType == null)
            {
                _logger.Error("Factory method failed to create type '" + type.FullName + "'.");
                return(null);
            }

            var instance = createdType as T;

            if (instance == null)
            {
                _logger.Error("Factory method assigned to '" + type.FullName + "' created a incompatible type '" +
                              createdType.GetType().FullName);
                return(null);
            }

            return(instance);
        }
        public bool TryResolve(ITypeSymbol type, out FactoryMethod instanceSource, out bool isAmbiguous, out IEnumerable <FactoryMethod> sourcesNotMatchingConstraints)
        {
            instanceSource = null !;
            sourcesNotMatchingConstraints = Array.Empty <FactoryMethod>();
            if (type is INamedTypeSymbol namedType)
            {
                if (_namedTypeBuckets.TryGetValue(namedType.OriginalDefinition, out var bucket))
                {
                    if (!bucket.TryResolve(type, out instanceSource, out isAmbiguous, out sourcesNotMatchingConstraints))
                    {
                        if (isAmbiguous)
                        {
                            return(false);
                        }
                    }
                }
            }
            else if (type is IArrayTypeSymbol or IPointerTypeSymbol or IFunctionPointerTypeSymbol)
            {
                if (!_otherTypesBucket.TryResolve(type, out instanceSource, out isAmbiguous, out sourcesNotMatchingConstraints))
                {
                    if (isAmbiguous)
                    {
                        return(false);
                    }
                }
            }

            if (_typeParameterBuckets.TryResolve(type, out var typeParamInstanceSource, out isAmbiguous, out var typeParamSourcesNotMatchingConstraints))
            {
                if (isAmbiguous)
                {
                    return(false);
                }
            }

            if (typeParamInstanceSource is null && instanceSource is null)
            {
                sourcesNotMatchingConstraints = sourcesNotMatchingConstraints.Concat(typeParamSourcesNotMatchingConstraints);
                return(false);
            }

            if (typeParamInstanceSource is null)
            {
                return(true);
            }

            if (instanceSource is null)
            {
                sourcesNotMatchingConstraints = Array.Empty <FactoryMethod>();
                instanceSource = typeParamInstanceSource;
                return(true);
            }

            sourcesNotMatchingConstraints = Array.Empty <FactoryMethod>();
            instanceSource = null !;
            isAmbiguous    = true;
            return(false);
        }
예제 #16
0
        public static Gate create(string type, string name)
        {
            Gate g = FactoryMethod <String, Gate> .create(type);

            g.Name  = name;
            g.Edges = new List <Gate>();
            return(g);
        }
예제 #17
0
파일: HttpFactory.cs 프로젝트: wingcd/utnt
        private void AddDefault(Type type, FactoryMethod handler)
        {
            if (_methods.ContainsKey(type))
            {
                return;
            }

            _methods[type] = handler;
        }
        public void Can_specify_to_use_default_ctor()
        {
            var container = new Container();

            container.Register <Ab>(made: FactoryMethod.DefaultConstructor());

            var ab = container.Resolve <Ab>();

            Assert.IsNotNull(ab);
        }
예제 #19
0
 public IAdaptableControl Invoke(FactoryInvocationArgs aArgs)
 {
     if (FactoryMethod == null)
     {
         throw new NullReferenceException("Method can't be null");
     }
     return((IAdaptableControl)FactoryMethod.Invoke(null, new object[1] {
         aArgs
     }));
 }
예제 #20
0
        private static FactoryMethod GetImportingConstructor(Request request)
        {
            var implementationType = request.ImplementationType;
            var constructors       = implementationType.GetAllConstructors().ToArrayOrSelf();
            var constructor        = constructors.Length == 1 ? constructors[0]
                : constructors.SingleOrDefault(x => x.GetAttributes(typeof(ImportingConstructorAttribute)).Any())
                                     .ThrowIfNull(Error.NoSingleCtorWithImportingAttr, implementationType);

            return(FactoryMethod.Of(constructor));
        }
        public void For_consistency_I_can_specify_FactoryMethod_to_be_a_constructor()
        {
            var container = new Container();

            container.Register <Ac>(made: Made.Of(FactoryMethod.Constructor()));

            var ac = container.WithDependencies(Parameters.Of.Type(_ => "x")).Resolve <Ac>();

            Assert.IsNotNull(ac);
        }
 public IMappedColumnItem Invoke(FactoryInvocationArgs aArgs)
 {
     if (FactoryMethod == null)
     {
         throw new NullReferenceException("Method can't be null");
     }
     return((IMappedColumnItem)FactoryMethod.Invoke(null, new object[1] {
         aArgs
     }));
 }
예제 #23
0
        public void RegisterLasyImmutable(TKey key, FactoryMethod <TProduct> method)
        {
            Guard.ArgumentNotNull("method", method);

            RegisterMethod(key, delegate {
                TProduct p = method();
                Unregister(key);
                RegisterImmutable(key, p);
                return(p);
            });
        }
예제 #24
0
        public void Can_specify_to_use_default_ctor_and_throw_correct_error_if_no_impl_type()
        {
            var container = new Container();

            container.Register <BaseA>(made: FactoryMethod.DefaultConstructor());

            var ex = Assert.Throws <ContainerException>(() =>
                                                        container.Resolve <BaseA>());

            Assert.AreEqual(Error.NameOf(Error.ImplTypeIsNotSpecifiedForAutoCtorSelection), ex.ErrorName);
        }
예제 #25
0
        public ActionResult TypeChart()
        {
            // Factory Method
            FactoryMethod factory1 = new FactoryMethod("Pie");
            string        type1    = factory1.typeChart;
            FactoryMethod factory2 = new FactoryMethod("Line");
            string        type2    = factory2.typeChart;

            ViewBag.Message = type1 + " and " + type2;
            return(View());
        }
예제 #26
0
        /// <summary>
        /// 文字列配列からIDマネージャーを作成する。
        /// IDオブジェクトのインデックスは文字列配列のインデックスに等しい。
        /// もし重複した文字列が含まれていた場合でもIDオブジェクトは登録されるがアクセスできなくなる。
        /// </summary>
        /// <param name="name_list">ID名の文字列配列</param>
        /// <param name="factory_method">IDオブジェクトを生成するメソッド</param>
        internal CubismIdManager(string[] name_list, FactoryMethod factory_method)
        {
            int count = name_list.Length;

            IdList = new IdType[count];
            for (int index = 0; index < count; index++)
            {
                IdList[index] = factory_method(name_list[index], index);
            }
            UnindexedIdList = new List <IdType>();
        }
예제 #27
0
 private static void Main()
 {
     for (var i = 0; i <= 3; i++)
     {
         var type = FactoryMethod.Get(i);
         if (type != null)
         {
             Console.WriteLine("This is this BEER: " + type.BeerFunctionality());
         }
     }
 }
예제 #28
0
 public virtual void Visit(FactoryMethod factoryMethod, State state)
 {
     foreach (var param in factoryMethod.Method.Parameters)
     {
         if (_exitFast)
         {
             return;
         }
         VisitCore(GetInstanceSource(param.Type, state, param), state);
     }
 }
예제 #29
0
 private bool TryGetMethod(IInvocation invocation, out FactoryMethod method)
 {
     if (methods.TryGetValue(invocation.Method, out method))
     {
         return(true);
     }
     if (invocation.Method.IsGenericMethod == false)
     {
         return(false);
     }
     return(methods.TryGetValue(invocation.Method.GetGenericMethodDefinition(), out method));
 }
예제 #30
0
        public void GenerateSet(int objectCount)
        {
            var result = new List <GameObject>();

            FactoryMethod[] barrierCreators = new FactoryMethod[] { CreateStone, CreateTree };
            FactoryMethod[] animalCreators  = new FactoryMethod[] { CreateFish, CreateDuck, CreateSparrow, CreateTurtle, CreateRabbit };

            int barrierCount = _random.Next(objectCount);

            for (int i = 0; i < objectCount; i++)
            {
                GameObject created = i < barrierCount ? barrierCreators[_random.Next(barrierCreators.Length)]() : animalCreators[_random.Next(animalCreators.Length)]();

                do
                {
                    created.Position = new Point(_random.Next(_map.Size.Width), _random.Next(_map.Size.Height));
                }while (!created.СanBeLocatedAt(created.Position));

                _gameObjectsContainer.Add(created);
            }
        }
		private bool TryGetMethod(IInvocation invocation, out FactoryMethod method)
		{
			if (methods.TryGetValue(invocation.Method, out method))
			{
				return true;
			}
			if (invocation.Method.IsGenericMethod == false)
			{
				return false;
			}
			return methods.TryGetValue(invocation.Method.GetGenericMethodDefinition(), out method);
		}