コード例 #1
0
        private void RegisterObjectFactoryMethod(ITemplate factory, MethodInfo method, FactoryMethodAttribute attrib)
        {
            Type objectType = method.ReturnType;

            if (method.GetParameters().Length != 0)
            {
                throw ExceptionHelper.FactoryParameterCountException();
            }

            if (attrib.FactoryId != null)
            {
                FactoryDelegate factoryDelegate = CreateMethodFactoryDelegate(factory, method);
                RegisterObjectFactoryMethod(attrib.FactoryId, factoryDelegate, attrib.InstanceMode);
            }
            else if (attrib.RegisterAs == FactoryType.DefaultForType)
            {
                FactoryDelegate factoryDelegate = CreateMethodFactoryDelegate(factory, method);
                Type            defaultType     = method.ReturnType;
                RegisterObjectFactoryMethod(defaultType, factoryDelegate, attrib.InstanceMode);
            }
            else
            {
                string          objectId        = method.Name;
                FactoryDelegate factoryDelegate = CreateMethodFactoryDelegate(factory, method);
                RegisterObjectFactoryMethod(objectId, factoryDelegate, attrib.InstanceMode);
            }
        }
        public void GetTypeFactory_ArgsMismatchInBuilding_ReturnsNull()
        {
            FactoryDelegate factory = DynamicMethodGenerator.GetTypeFactory(
                typeof(Example),
                typeof(string), typeof(string), typeof(string));

            Assert.Null(factory);
        }
コード例 #3
0
 public static T GetFromParentOrCurrent<T>(FactoryDelegate<T> fd, FactoryInfo<T> fi, IResolverContext r)
 {
     var id = fi.Id;
     for (var s = r.CurrentScope; s != null; s = s.Parent)
         if (s.TryGet(out var res, id))
             return (T)res;
     return fd(r);
 }
        public void GetTypeFactory_1MillionInstantiationsAlt_PerformsInAround50ms()
        {
            FactoryDelegate factory = DynamicMethodGenerator.GetTypeFactory(typeof(Example), Type.EmptyTypes);

            for (long i = 0; i < MaxCount; i++)
            {
                Example instance = (Example)factory();
            }
        }
コード例 #5
0
        private ObjectFactoryInfo CreateObjectFactory(string displayName, FactoryDelegate factoryDelegate, InstanceMode instanceMode)
        {
            ObjectFactoryInfo factory = new ObjectFactoryInfo();

            factory.FactoryDelegate = factoryDelegate;
            factory.InstanceMode    = instanceMode;
            factory.DisplayName     = displayName;
            return(factory);
        }
コード例 #6
0
        public override DataPresenter With(FactoryDelegate <DataReader> createDataReader)
        {
            Log.Enter(nameof(FactoryDelegate <DataReader>));

            _createDataReader = createDataReader;

            Log.Exit();
            return(this);
        }
        public void GetTypeFactory_NullCtorInput_ThrowsArgumentNullException()
        {
            ArgumentNullException ex = Assert.Throws <ArgumentNullException>(
                delegate()
            {
                FactoryDelegate factory = DynamicMethodGenerator.GetTypeFactory((ConstructorInfo)null);
            });

            Assert.Equal("ctor", ex.ParamName);
        }
        public void GetTypeFactory_NullTypeInputAlt_ThrowsArgumentNullException()
        {
            ArgumentNullException ex = Assert.Throws <ArgumentNullException>(
                delegate()
            {
                FactoryDelegate factory = DynamicMethodGenerator.GetTypeFactory((Type)null, Type.EmptyTypes);
            });

            Assert.Equal("type", ex.ParamName);
        }
コード例 #9
0
        private FactoryDelegate CreateMethodFactoryDelegate(ITemplate factory, MethodInfo method)
        {
            ConstantExpression   instance        = Expression.Constant(factory);
            MethodCallExpression call            = Expression.Call(instance, method);
            Expression           body            = Expression.TypeAs(call, typeof(object));
            LambdaExpression     lambda          = Expression.Lambda(typeof(FactoryDelegate), body);
            FactoryDelegate      factoryDelegate = (FactoryDelegate)lambda.Compile();

            return(factoryDelegate);
        }
コード例 #10
0
        /// <summary>
        /// Register the given factory delegate to be called when the container is
        /// asked to resolve <typeparamref name="=TTypeToBuild"/> and <paramref name="name"/>.
        /// </summary>
        /// <typeparam name="TTypeToBuild">Type that will be requested from the container.</typeparam>
        /// <param name="name">The name that will be used when requesting to resolve this type.</param>
        /// <param name="factoryMethod">Delegate to invoke to create the instance.</param>
        /// <returns>The container extension object this method was invoked on.</returns>
        public IStaticFactoryConfiguration RegisterFactory <TTypeToBuild>(
            string name, FactoryDelegate factoryMethod)
        {
            FactoryBuildPlanDelegate planDelegate = delegate { return(factoryMethod(Container)); };

            Context.Policies.Set <IBuildPlanPolicy>(
                new FactoryDelegateBuildPlanPolicy(planDelegate),
                NamedTypeBuildKey.Make <TTypeToBuild>(name));
            return(this);
        }
コード例 #11
0
 FactoryDelegate this [string s]
 {
     set
     {
         var = value;
     }
     get
     {
         return(var);
     }
 }
コード例 #12
0
        /// <summary>
        /// Creates the default thread local.
        /// </summary>
        /// <returns></returns>
        public static IThreadLocal <T> CreateDefaultThreadLocal <T>(FactoryDelegate <T> factoryDelegate)
            where T : class
        {
            var localFactory = DefaultThreadLocalFactory;

            if (localFactory == null)
            {
                throw new ApplicationException("default thread local factory is not set");
            }

            return(localFactory.CreateThreadLocal(factoryDelegate));
        }
コード例 #13
0
 public ObjectPool(FactoryDelegate factory, string containerN, int quantity = 5)
 {
     _objects             = new Stack <GameObject>();
     _factory             = factory;
     _containerGameObject = GameObject.FindGameObjectWithTag(containerN);
     if (quantity >= 0)
     {
         for (int i = 0; i < quantity; i++)
         {
             _objects.Push(Create());
         }
     }
 }
        public void GetTypeFactory_ArgsMissingWhenCalling_ThrowsArgumentNullException()
        {
            FactoryDelegate factory = DynamicMethodGenerator.GetTypeFactory(
                typeof(Example),
                typeof(string), typeof(string), typeof(string), typeof(int), typeof(int), typeof(int), typeof(string), typeof(string), typeof(string));

            Assert.NotNull(factory);

            TypeLoadException ex = Assert.Throws <TypeLoadException>(
                delegate()
            {
                var actual = (Example)factory("alpha", "bravo", "charlie", -1, -2, -3);
            });
        }
        public void GetTypeFactory_ArgsTypeMismatchWhenCalling_ThrowsArgumentNullException()
        {
            FactoryDelegate factory = DynamicMethodGenerator.GetTypeFactory(
                typeof(Example),
                typeof(string), typeof(string), typeof(string), typeof(int), typeof(int), typeof(int), typeof(string), typeof(string), typeof(string));

            Assert.NotNull(factory);

            InvalidCastException ex = Assert.Throws <InvalidCastException>(
                delegate()
            {
                var actual = (Example)factory(1, 2, 3, 4, 5, 6, 7, 8, 9);
            });
        }
コード例 #16
0
ファイル: FactoryCompiler.cs プロジェクト: csteeg/BoC
partial         static void CompileToDelegate(Expression expression, ref FactoryDelegate result)
        {
            var method = new DynamicMethod(string.Empty,
                typeof(object), _factoryDelegateArgTypes,
                typeof(Container).Module, skipVisibility: true);

            var il = method.GetILGenerator();

            var emitted = EmittingVisitor.TryVisit(expression, il);
            if (emitted)
            {
                il.Emit(OpCodes.Ret);
                result = (FactoryDelegate)method.CreateDelegate(typeof(FactoryDelegate));
            }
        }
コード例 #17
0
ファイル: RemotingServer.cs プロジェクト: koma00/GatewayIrbis
        /// <summary>
        /// Get service of given type.
        /// </summary>
        /// <param name="serviceType"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public virtual object GetService
        (
            Type serviceType,
            ServiceContext context)
        {
            Trace.WriteLine("in RemotingServer.GetService");
            if (Paused)
            {
                throw new ServicePausedException();
            }
            FactoryDelegate factory = _map [serviceType];
            object          service = factory();

            return(service);
        }
コード例 #18
0
        static partial void CompileToDelegate(Expression expression, ref FactoryDelegate result)
        {
            var method = new DynamicMethod(string.Empty,
                                           typeof(object), _factoryDelegateArgTypes,
                                           typeof(Container).Module, skipVisibility: true);

            var il = method.GetILGenerator();

            var emitted = EmittingVisitor.TryVisit(expression, il);

            if (emitted)
            {
                il.Emit(OpCodes.Ret);
                result = (FactoryDelegate)method.CreateDelegate(typeof(FactoryDelegate));
            }
        }
コード例 #19
0
ファイル: XperThreadLocal.cs プロジェクト: ikvm/nesper
        /// <summary>
        /// Initializes a new instance of the <see cref="XperThreadLocal{T}"/> class.
        /// </summary>
        /// <param name="factory">The factory.</param>
        public XperThreadLocal(FactoryDelegate <T> factory)
        {
            _primeIndex = 0;

            var tableSize = Prime.HashPrimes[_primeIndex];

            _hashIndex = new int[tableSize];
            for (int ii = 0; ii < tableSize; ii++)
            {
                _hashIndex[ii] = -1;
            }

            _nodeTable = new Node[tableSize];

            _valueFactory = factory;
            _wLock        = new SlimLock();
        }
コード例 #20
0
        /// <summary>
        /// Register a new factory with the registery. Replaces an existing
        /// factory if the scheme is already registered.
        /// </summary>
        static public void Register(string scheme, FactoryDelegate factory)
        {
            if (_registry == null)
            {
                _registry = new Dictionary <string, FactoryDelegate>(16);
            }

            // Register Scheme
            if (!_registry.ContainsKey(scheme))
            {
                _registry.Add(scheme, factory);
            }
            else
            {
                _registry[scheme] = factory;
            }
        }
            public IFoo GetOrCreate2(IResolverContext ctx, FactoryDelegate <Func <string, IFoo> > fooFactory, string address)
            {
                // fancy ensuring that we have a single new Scope created and stored
                var scopeEntry = _scopes.GetEntryOrDefault(address);

                if (scopeEntry == null)
                {
                    Ref.Swap(ref _scopes, address, (x, a) => x.AddOrKeep(a));
                    scopeEntry = _scopes.GetEntryOrDefault(address);
                }

                lock (scopeEntry)
                    if (scopeEntry.Value == null || scopeEntry.Value.IsDisposed)
                    {
                        scopeEntry.Value = ctx.OpenScope(address);
                    }

                return(fooFactory(scopeEntry.Value).Invoke(address));
            }
        public void GetTypeFactory_CtorNoArgsAlt_ReturnsCorrectlyInstantiatedObject()
        {
            var expected = new Example();

            FactoryDelegate factory = DynamicMethodGenerator.GetTypeFactory(typeof(Example), Type.EmptyTypes);

            Assert.NotNull(factory);
            var actual = (Example)factory();

            var getters =
                from m in typeof(Example).GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy)
                let g = DynamicMethodGenerator.GetGetter(m)
                        where (g != null)
                        select g;

            foreach (GetterDelegate getter in getters)
            {
                // assert all of the fields and properties are equal
                Assert.Equal(getter(expected), getter(actual));
            }
        }
コード例 #23
0
        public override void Dispose()
        {
            Log.Enter();

            Log.Info($"Terminating DataReader session: {_dataReaderSession != null}");
            _dataReaderSession?.Dispose();
            _dataReaderSession = null;
            _createDataReader  = null;

            Log.Info($"Disposing data provider: {_dataProvider != null}");
            _dataProvider?.Dispose();
            _dataProvider = null;

            Log.Info($"Disposing ESPlayer: {_esPlayer != null}");
            _esPlayer?.Dispose();
            _esPlayer = null;

            ErrorHandler = null;
            EosHandler   = null;

            Log.Exit();
        }
コード例 #24
0
ファイル: RemotingServer.cs プロジェクト: koma00/GatewayIrbis
        private static void _Add
        (
            Type intf,
            Type implementor)
        {
            MethodInfo miFound = null;

            foreach (
                MethodInfo mi in
                implementor.GetMethods
                (
                    BindingFlags.Static | BindingFlags.Public
                    | BindingFlags.NonPublic))
            {
                if (mi.GetCustomAttributes
                    (
                        typeof(FactoryMethodAttribute),
                        false) != null)
                {
                    miFound = mi;
                    break;
                }
            }
            if (miFound == null)
            {
                throw new ArgumentException("implementor");
            }
            FactoryDelegate fd =
                (FactoryDelegate)
                Delegate.CreateDelegate
                (
                    typeof(FactoryDelegate),
                    null,
                    miFound,
                    true);

            _map [intf] = fd;
        }
        public void GetTypeFactory_CtorExtraArgs_IgnoresAndReturnsCorrectlyInstantiatedObject()
        {
            var expected = new Example("alpha", "bravo", "charlie", -1, -2, -3, "deer", "sun", "myself");

            FactoryDelegate factory = DynamicMethodGenerator.GetTypeFactory(
                typeof(Example),
                typeof(string), typeof(string), typeof(string), typeof(int), typeof(int), typeof(int), typeof(string), typeof(string), typeof(string));

            Assert.NotNull(factory);
            var actual = (Example)factory("alpha", "bravo", "charlie", -1, -2, -3, "deer", "sun", "myself", 4, 5, 6, "extra", false);

            var getters =
                from m in typeof(Example).GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy)
                let g = DynamicMethodGenerator.GetGetter(m)
                        where (g != null)
                        select g;

            foreach (GetterDelegate getter in getters)
            {
                // assert all of the fields and properties are equal
                Assert.Equal(getter(expected), getter(actual));
            }
        }
コード例 #26
0
ファイル: FastThreadLocal.cs プロジェクト: ecakirman/nesper
 /// <summary>
 /// Create a thread local object of the specified type param.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="factory"></param>
 /// <returns></returns>
 public IThreadLocal <T> CreateThreadLocal <T>(FactoryDelegate <T> factory) where T : class
 {
     return(new FastThreadLocal <T>(factory));
 }
コード例 #27
0
ファイル: FastThreadLocal.cs プロジェクト: ecakirman/nesper
 /// <summary>
 /// Initializes a new instance of the <see cref="FastThreadLocal&lt;T&gt;"/> class.
 /// </summary>
 /// <param name="factory">The factory.</param>
 public FastThreadLocal(FactoryDelegate <T> factory)
 {
     _instanceId  = AllocateIndex();
     _dataFactory = factory;
 }
コード例 #28
0
 public static T Set(FactoryDelegate <T> factoryMethod)
 {
     factory = factoryMethod;
     return(Instance);
 }
コード例 #29
0
ファイル: SystemThreadLocal.cs プロジェクト: valmac/nesper
 /// <summary>
 /// Initializes a new instance of the <see cref="SystemThreadLocal&lt;T&gt;"/> class.
 /// </summary>
 /// <param name="factory">The factory used to create values when not found.</param>
 public SystemThreadLocal(FactoryDelegate <T> factory)
 {
     m_dataStoreSlot = Thread.AllocateDataSlot();
     m_dataFactory   = factory;
 }
コード例 #30
0
	FactoryDelegate this [string s]
	{
		set { var = value; }
		get { return var; }
	}
コード例 #31
0
ファイル: FactoryCompiler.cs プロジェクト: RalfvandenBurg/BoC
partial         static void CompileToMethod(Expression<FactoryDelegate> factoryExpression, Rules rules, ref FactoryDelegate result)
        {
            if (!rules.FactoryDelegateCompilationToDynamicAssembly)
                return;

            result.ThrowIf(result != null);

            var typeName = "Factory" + Interlocked.Increment(ref _typeId);
            var typeBuilder = GetDynamicAssemblyModuleBuilder().DefineType(typeName, TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Abstract);

            var methodBuilder = typeBuilder.DefineMethod(
                "GetService",
                MethodAttributes.Public | MethodAttributes.Static,
                typeof(object),
                new[] { typeof(AppendableArray), typeof(IResolverContextProvider), typeof(IScope) });

            factoryExpression.CompileToMethod(methodBuilder);

            var dynamicType = typeBuilder.CreateType();
            result = (FactoryDelegate)Delegate.CreateDelegate(typeof(FactoryDelegate), dynamicType.GetMethod("GetService"));
        }
コード例 #32
0
 /// <summary>
 /// Creates a thread local instance.
 /// </summary>
 /// <returns></returns>
 public static IThreadLocal <T> Create <T>(FactoryDelegate <T> factoryDelegate)
     where T : class
 {
     return(CreateDefaultThreadLocal(factoryDelegate));
 }
コード例 #33
0
 public abstract DataPresenter With(FactoryDelegate <DataReader> createDataReader);