/// <summary>
        /// Compiles <paramref name="unit"/> and returns generated assembly.
        /// </summary>
        /// <param name="unit">Source code compile unit.</param>
        /// <returns>Generated assembly.</returns>
        private Assembly CompileCodeUnit(CodeCompileUnit unit)
        {
            IStaticCompiler compiler = compilerFactory.CreateStatic();

            string          assemblyFilePath = Path.Combine(configuration.TempDirectory(), nameFormatter.FormatAssemblyFileName());
            ICompilerResult result           = compiler.FromUnit(unit, assemblyFilePath);

            if (!result.IsSuccess)
            {
                // Save source code if compilation was not successfull.

                CodeDomProvider provider       = CodeDomProvider.CreateProvider("CSharp");
                string          sourceCodePath = Path.Combine(configuration.TempDirectory(), nameFormatter.FormatSourceCodeFileName());

                using (StreamWriter writer = new StreamWriter(sourceCodePath))
                {
                    provider.GenerateCodeFromCompileUnit(unit, writer, new CodeGeneratorOptions());
                }

                Ensure.Exception.UnCompilableSource(sourceCodePath);
            }

            // Load compiled assembly.
            return(ReflectionFactory.FromCurrentAppDomain().LoadAssembly(assemblyFilePath));
        }
コード例 #2
0
        public void TestPostConstructor()
        {
            var factory        = new ReflectionFactory();
            var reflectedClass = factory.Create(typeof(MockIClassWithAttributes));

            Assert.AreEqual(1, reflectedClass.methods.Length);
        }
コード例 #3
0
        public void TestInjectField()
        {
            var factory        = new ReflectionFactory();
            var reflectedClass = factory.Create(typeof(MockIClassWithAttributes));

            Assert.AreEqual(1, reflectedClass.fields.Length);
        }
コード例 #4
0
        public void TestReflectedClassCreation()
        {
            var factory        = new ReflectionFactory();
            var reflectedClass = factory.Create(typeof(MockIClassWithoutAttributes));

            Assert.NotNull(reflectedClass);
        }
コード例 #5
0
 public void CreateUserAccountRepository_CreatesUserAccountRepository()
 {
     var sub = new ReflectionFactory(typeof(TestRepo));
     var instance = sub.CreateUserAccountRepository();
     Assert.IsNotNull(instance);
     Assert.IsInstanceOfType(instance, typeof(TestRepo));
 }
コード例 #6
0
ファイル: SqlServerExtension.cs プロジェクト: Ljyi/L_Example
        /// <summary>
        ///  设置属性的值扩展
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="property"></param>
        /// <param name="entity"></param>
        /// <param name="value"></param>
        /// <param name="isCache"></param>
        public static void SetPropertyValue <TEntity, TValue>(this PropertyInfo property, TEntity entity, TValue value, bool isCache = true)
            where TEntity : class
        {
            var propertyInfo = ReflectionFactory.Create <TEntity, TEntity, TValue>(property, property, isCache);

            propertyInfo.SetValue(entity, value);
        }
コード例 #7
0
    static void Main(string[] args)
    {
        // Here's the usage of a "traditional" factory, which returns objects that implement a common interface.
        // This is a great pattern for a lot of different scenarios.
        // The only downside is that you have to update your factory class whenever you add a new class.
        TraditionalFactory.Create("A_ID").DoIt();
        TraditionalFactory.Create("B_ID").DoIt();
        Console.ReadKey();

        // But what if we make a class that uses reflection to find attributes of classes it can create? Reflection!
        // This works great and now all we have to do is add an attribute to new classes and this thing will just work.
        // (It could also be more generic in its input / output, but I simplified it for this example)
        ReflectionFactory.Create("A_ID").DoIt();
        ReflectionFactory.Create("B_ID").DoIt();
        // Wait, that's great and all, but everyone always says reflection is so slow, and this thing's going to reflect
        // on every object creation...that's not good right?
        Console.ReadKey();

        // So I created this new factory class which gives the speed of the traditional factory combined with the flexibility
        // of the reflection-based factory.
        // The reflection done here is only performed once. After that, it is as if the Create() method is using a switch statement
        Factory <string, IDoSomething> .Create("A_ID").DoIt();

        Factory <string, IDoSomething> .Create("B_ID").DoIt();

        Console.ReadKey();
    }
コード例 #8
0
        public void TestConstructorWhenNoConstruct()
        {
            var factory        = new ReflectionFactory();
            var reflectedClass = factory.Create(typeof(MockIClassWithoutAttributes));

            Assert.NotNull(reflectedClass.constructor);
            Assert.AreEqual(0, reflectedClass.constructorParameters.Length);
        }
コード例 #9
0
        public void CreateUserAccountRepository_CreatesUserAccountRepository()
        {
            var sub      = new ReflectionFactory(typeof(TestRepo));
            var instance = sub.CreateUserAccountRepository();

            Assert.IsNotNull(instance);
            Assert.IsInstanceOfType(instance, typeof(TestRepo));
        }
コード例 #10
0
 private IEnumerable <DynamicRegistration> GetX(Type serviceType, object key)
 {
     if (serviceType == typeof(X))
     {
         return new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(A))) }
     }
     ;
     return(null);
 }
コード例 #11
0
ファイル: BaseCommand.cs プロジェクト: divilla/Whizz
        protected void BindParameters(Type type)
        {
            var getters = ReflectionFactory.GetterDelegatesByPropertyName(type, Repository.DbCase);

            foreach (NpgsqlParameter commandParameter in Command.Parameters)
            {
                commandParameter.Value = getters[commandParameter.ParameterName](Data);
            }
        }
コード例 #12
0
        public void ReflectionFactoryCreate_CreateReflectionInfo_paramsConstructorCorrect()
        {
            //Arrange
            ReflectionFactory reflectionFactory = new ReflectionFactory();
            //Act
            ReflectionInfo reflectionInfo = reflectionFactory.Create(typeof(someClass_d));

            //Assert
            Assert.AreEqual(false, reflectionInfo.paramsConstructor == null);
        }
コード例 #13
0
        public void ReflectionFactoryCreate_CreateReflectionInfo_postConstructorsCorrect()
        {
            //Arrange
            ReflectionFactory reflectionFactory = new ReflectionFactory();
            //Act
            ReflectionInfo reflectionInfo = reflectionFactory.Create(typeof(someClass_e));

            //Assert
            Assert.AreEqual(2, reflectionInfo.methods.Length);
        }
コード例 #14
0
        public void ReflectionFactoryCreate_CreateReflectionInfo_typeCorrect()
        {
            //Arrange
            ReflectionFactory reflectionFactory = new ReflectionFactory();
            //Act
            ReflectionInfo reflectionInfo = reflectionFactory.Create(typeof(someClass_d));

            //Assert
            Assert.AreEqual(typeof(someClass_d), reflectionInfo.type);
        }
コード例 #15
0
ファイル: RegisterResolve.cs プロジェクト: dadhi/DryIoc
    public void Example()
    {
        var container = new Container();

        container.Register(typeof(IA), ReflectionFactory.Of(typeof(A), Reuse.Singleton));

        var a = container.Resolve <IA>();

        Assert.IsInstanceOf <A>(a);
    }
コード例 #16
0
        public void TestConstructorWithConstruct()
        {
            var factory        = new ReflectionFactory();
            var reflectedClass = factory.Create(typeof(MockIClassWithAttributes));

            Assert.IsNull(reflectedClass.constructor);
            Assert.NotNull(reflectedClass.paramsConstructor);
            Assert.AreEqual(1, reflectedClass.constructorParameters.Length);
            Assert.AreEqual(typeof(MockClassToDepend), reflectedClass.constructorParameters[0].type);
        }
コード例 #17
0
        public void ReflectionFactoryCreate_CreateReflectionInfo_fieldsCorrect()
        {
            //Arrange
            ReflectionFactory reflectionFactory = new ReflectionFactory();
            //Act
            ReflectionInfo reflectionInfo = reflectionFactory.Create(typeof(someClass_f));

            //Assert
            Assert.AreEqual(4, reflectionInfo.fields.Length);
        }
コード例 #18
0
        public Dictionary <string, string> Format(object item, int depth)
        {
            if (depth > MaxDepth || item == null)
            {
                return(new Dictionary <string, string>());
            }
            var result = new Dictionary <string, string>();
            var props  = ReflectionFactory.GetProperties(item);

            foreach (var prop in props)
            {
                // see if we have a parser for this property
                var parser = Formatters.GetFormatter(prop.PropertyType);
                if (parser == null)
                {
                    continue;
                }

                try
                {
                    var val = prop.GetValue(item);
                    if (val == null)
                    {
                        continue;
                    }
                    var propKeyValue = parser.Format(val, depth + 1);

                    foreach (var kv in propKeyValue)
                    {
                        var    suffix = string.IsNullOrWhiteSpace(kv.Key) ? string.Empty : "_" + kv.Key;
                        string key    = prop.Name + suffix;
                        string value;
                        if (key.Length > 4000)
                        {
                            key = kv.Key.Substring(0, 4000); //short circuit strings larger than 8kb
                        }
                        if (!string.IsNullOrEmpty(kv.Value) && kv.Value.Length > 4000)
                        {
                            value = kv.Value.Substring(0, 4000);
                        }
                        else
                        {
                            value = kv.Value;
                        }
                        result[key] = value;
                    }
                }
                catch (Exception e) { } // swallow exception
            }

            return(result);
        }
コード例 #19
0
        public void Create_WithNullInstanceResolvers_ShouldNotThrow()
        {
            ReflectionFactory sut = createSut();

            try
            {
                sut.Create(typeof(NullLogger).GetConstructors().FirstOrDefault(), null);
            }
            catch (Exception)
            {
                Assert.True(false, "Should not throw exception");
            }
        }
コード例 #20
0
            public void Base()
            {
                IDependencyContainer root = new SimpleDependencyContainer();

                IReflectionService reflectionService = ReflectionFactory.FromCurrentAppDomain();

                using (ITypeExecutorService executorService = reflectionService.PrepareTypeExecutors())
                {
                    executorService.AddQueryHandlers(root);
                }

                IQueryHandler <Q1, R1> handler1 = root.Resolve <IQueryHandler <Q1, R1> >();
                IQueryHandler <Q2, R2> handler2 = root.Resolve <IQueryHandler <Q2, R2> >();
            }
        public void There_should_not_be_NRE()
        {
            var c = new Container();

            var prop = typeof(C).GetProperty("P", BindingFlags.NonPublic | BindingFlags.Static);

            var factory = new ReflectionFactory(typeof(string), made: Made.Of(prop));

            c.Register(factory, typeof(string), null, IfAlreadyRegistered.Replace, true);

            var s = c.Resolve <string>();

            Assert.AreEqual("boo!", s);
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: kolszer/DesignPatterns-1
        private static void ReflectionFactoryTest()
        {
            Logger.AddTestStep("Testing ReflectionFactory");

            Furniture furniture = null;

            furniture = ReflectionFactory.GetFurniture <CoffeeTable>();
            Console.WriteLine(string.Format("We ordered coffee table and we've got: {0}", furniture.Name));

            var assembly = Assembly.LoadFile(Environment.CurrentDirectory + @"\Library.dll");

            furniture = ReflectionFactory.GetFurniture(assembly.ExportedTypes.First().FullName);
            Console.WriteLine(string.Format("We ordered large desk and we've got: {0}", furniture.Name));
        }
コード例 #23
0
        public static void testRoutes()
        {
            Controllers.Routes.Route.register();
            Controllers.Routes.Route.Go("index");
            Controllers.Routes.Route.Go("index", "Index");
            Controllers.Routes.Route.Go("Index", "Get", 1);
            Controllers.Routes.Route.Go("test", "Test");
            Controllers.Routes.Route.Go("test", "Test1", 2, "A12");
            var sarr = ReflectionFactory.MakeSources();

            foreach (var s in sarr)
            {
                Console.WriteLine("创建 " + s.ShowInfo());
            }
            ReflectionFactory.ShowSource("Test1Source");
        }
コード例 #24
0
        public void Can_replace_normal_with_dynamic_and_dynamic_with_dynamic_registration()
        {
            var container = new Container(rules => rules.WithDynamicRegistrations(
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                    ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(A)), IfAlreadyRegistered.Replace) }
                    : null,
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                    ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(A)), IfAlreadyRegistered.Replace) }
                    : null));

            container.Register <X, B>();

            var x = container.Resolve <X>();

            Assert.IsInstanceOf <A>(x);
        }
コード例 #25
0
        public void Will_keep_first_keyed_registration_by_default()
        {
            var container = new Container(rules => rules.WithDynamicRegistrations(
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                    ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(A)), serviceKey: "a") }
                    : null,
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                    ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(B)), serviceKey: "a") }
                    : null));

            container.Register <X>(serviceKey: "a");

            var a = container.Resolve <X>("a");

            Assert.IsInstanceOf <X>(a);
        }
コード例 #26
0
        public void Can_replace_keyed_registration()
        {
            var container = new Container(rules => rules.WithDynamicRegistrations(
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                 ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(A)), IfAlreadyRegistered.Replace, "a") }
                 : null,
                                              (serviceType, serviceKey) => serviceType == typeof(X)
                    ? new[] { new DynamicRegistration(ReflectionFactory.Of(typeof(B)), IfAlreadyRegistered.Replace, "a") }
                    : null));

            container.Register <X>(serviceKey: "a");

            var a = container.Resolve <X>("a");

            Assert.IsInstanceOf <B>(a);
        }
コード例 #27
0
ファイル: RegisterResolve.cs プロジェクト: dadhi/DryIoc
    public void Example()
    {
        // Allows registration of B which implements IDisposable as Transient, which is default `RegisterMany` reuse.
        var container = new Container(rules => rules
                                      .WithTrackingDisposableTransients());

        // Registers X, Y and A itself with A implementation
        container.RegisterMany <A>();

        // Registers only X and Y, but not A itself
        container.RegisterMany <A>(serviceTypeCondition: type => type.IsInterface);

        // X, Y, A are sharing the same singleton
        container.RegisterMany <A>(Reuse.Singleton);
        Assert.AreSame(container.Resolve <X>(), container.Resolve <Y>());

        // Registers X, Y with A and X with B
        // IDisposable is too general to be considered as a service type,
        // see the full list of excluded types after example below.
        container.RegisterMany(
            new[] { typeof(A), typeof(B) },
            serviceTypeCondition: type => type.IsInterface);

        // Registers only X with A and X with B
        container.RegisterMany(
            new[] { typeof(A), typeof(B) },
            serviceTypeCondition: type => type == typeof(X));

        // The same as above if A and B in the same assembly.
        // Plus registers the rest of the types from assembly of A.
        container.RegisterMany(new[] { typeof(A).Assembly }, type => type == typeof(X));

        // Made.Of expression is supported too
        container.RegisterMany(Made.Of(() => CreateA()));

        // Explicit about what services to register
        container.RegisterMany(new[] { typeof(X), typeof(Y) }, typeof(A));

        // Provides full control to you
        container.RegisterMany(new[] { typeof(A).Assembly },
                               getServiceTypes: implType => implType.GetImplementedServiceTypes(),
                               getImplFactory: implType => ReflectionFactory.Of(implType,
                                                                                implType.IsAssignableTo <IDisposable>() ? Reuse.Scoped : Reuse.Transient,
                                                                                FactoryMethod.ConstructorWithResolvableArguments));
    }
コード例 #28
0
        public void Resolve_mock_for_non_registered_service()
        {
            var container = new Container(rules => rules.WithUnknownServiceResolvers(request =>
            {
                var serviceType = request.ServiceType;
                if (!serviceType.IsAbstract)
                {
                    return(null); // Mock interface or abstract class only.
                }
                return(ReflectionFactory.Of(made: Made.Of(
                                                serviceReturningExpr: () => Substitute.For(Arg.Index <Type[]>(0), Arg.Index <object[]>(1)),
                                                _ => new[] { serviceType }, _ => (object[])null)));
            }));

            var sub = container.Resolve <INotImplementedService>();

            Assert.That(sub, Is.InstanceOf <INotImplementedService>());
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: intotf/netExample
        static void Main(string[] args)
        {
            var serviceA = new ServiceClassA();
            var serviceB = new ServiceClassB();
            var clientA  = new ClientClass(serviceA);

            clientA.ShowInfo();
            var clientB = new ClientClass(serviceA);

            clientB.ShowInfo();

            var btn = ReflectionFactory.MakeButton();

            Console.WriteLine(btn.ShowInfo());


            Console.ReadLine();
        }
コード例 #30
0
            public void ConcreteType()
            {
                IQueryHandlerCollection collection = new DefaultQueryDispatcher();

                IReflectionService reflectionService = ReflectionFactory.FromCurrentAppDomain();

                using (ITypeExecutorService executorService = reflectionService.PrepareTypeExecutors())
                {
                    executorService.AddQueryHandlers(collection);
                }

                IQueryHandler <Q3, R3> handler3;

                Assert.AreEqual(true, collection.TryGet(out handler3));
                IQueryHandler <Q4, R4> handler4;

                Assert.AreEqual(false, collection.TryGet(out handler4));
            }
コード例 #31
0
            public void Base()
            {
                IQueryHandlerCollection collection = new DefaultQueryDispatcher();

                IReflectionService reflectionService = ReflectionFactory.FromCurrentAppDomain();

                using (ITypeExecutorService executorService = reflectionService.PrepareTypeExecutors())
                {
                    executorService.AddQueryHandlers(collection);
                }

                IQueryHandler <Q1, R1> handler1;

                Assert.AreEqual(true, collection.TryGet(out handler1));
                IQueryHandler <Q2, R2> handler2;

                Assert.AreEqual(true, collection.TryGet(out handler2));
            }
コード例 #32
0
ファイル: DryIoc.cs プロジェクト: nutrija/revenj
        public static void Default(IRegistry registry)
        {
            registry.ResolutionRules.UnregisteredServices =
                registry.ResolutionRules.UnregisteredServices.Append(
                    ResolveEnumerableAsStaticArray,
                    ResolveManyDynamically);

            var funcFactory = new FactoryProvider(
                (_, __) => new DelegateFactory(GetFuncExpression, Reuse.Singleton),
                GenericWrapperSetup.With(t => t[t.Length - 1]));
            foreach (var funcType in FuncTypes)
                registry.Register(funcType, funcFactory);

            var lazyFactory = new ReflectionFactory(typeof(Lazy<>),
                getConstructor: t => t.GetConstructor(new[] { typeof(Func<>).MakeGenericType(t.GetGenericArguments()) }),
                setup: GenericWrapperSetup.Default);
            registry.Register(typeof(Lazy<>), lazyFactory);

            var metaFactory = new FactoryProvider(GetMetaFactoryOrDefault, GenericWrapperSetup.With(t => t[0]));
            registry.Register(typeof(Meta<,>), metaFactory);

            var debugExprFactory = new FactoryProvider(
                (_, __) => new DelegateFactory(GetDebugExpression),
                GenericWrapperSetup.Default);
            registry.Register(typeof(DebugExpression<>), debugExprFactory);
        }