This class is consumed by the Fody.ModuleInit and invokes the static Initialize ONCE for the entire run, ensuring that within the AppDomain, the current/base directory isn't changed by any code running directly or indirectly by the tests. (i.e. running MSBuild tests/builds sometimes changes the base directory)
 public static void ResetStateAndInitMsal()
 {
     ModuleInitializer.ForceModuleInitializationTestOnly();
     ResetState();
     new AadInstanceDiscovery(null, null, true);
     new ValidatedAuthoritiesCache(true);
 }
예제 #2
0
 public void NullContainerThrows()
 {
     var ex = Assert.Throws <ArgumentNullException>(() =>
     {
         ModuleInitializer loader = new ModuleInitializer(null);
     });
 }
예제 #3
0
        private void InitViz3DControl()
        {
            try
            {
                if (vizcore3d == null)
                {
                    // Initialize VIZCore3D.NET
                    ModuleInitializer.Run();

                    // Construction
                    vizcore3d         = new VIZCore3DControl();
                    vizcorehost.Child = vizcore3d;

                    // Event
                    vizcore3d.OnInitializedVIZCore3D += VIZCore3D_OnInitializedVIZCore3D;
                }

                //NextStepDispatcher next = new NextStepDispatcher();
                //next.NextStep += OnConstructNext;
                //next.Start();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #4
0
        protected override void RegisterRequiredTypes(IContainerRegistry containerRegistry)
        {
            RegisterRequiredTypesCalled = true;

            base.RegisterRequiredTypes(containerRegistry);

            var logger = new TextLogger();

            MockContainer.Setup(x => x.Resolve(typeof(ILoggerFacade))).Returns(logger);

            var moduleInitializer = new ModuleInitializer(MockContainer.Object, logger);

            MockContainer.Setup(x => x.Resolve(typeof(IModuleInitializer))).Returns(moduleInitializer);
            MockContainer.Setup(x => x.Resolve(typeof(IModuleManager))).Returns(new ModuleManager(moduleInitializer, DefaultModuleCatalog, logger));
            MockContainer.Setup(x => x.Resolve(typeof(IRegionBehaviorFactory))).Returns(new RegionBehaviorFactory(MockContainer.Object));

            var regionBehaviorFactory = new RegionBehaviorFactory(MockContainer.Object);

            MockContainer.Setup(x => x.Resolve(typeof(IRegionBehaviorFactory))).Returns(regionBehaviorFactory);

            MockContainer.Setup(x => x.Resolve(typeof(RegionAdapterMappings))).Returns(new RegionAdapterMappings());
            MockContainer.Setup(x => x.Resolve(typeof(SelectorRegionAdapter))).Returns(new SelectorRegionAdapter(regionBehaviorFactory));
            MockContainer.Setup(x => x.Resolve(typeof(ItemsControlRegionAdapter))).Returns(new ItemsControlRegionAdapter(regionBehaviorFactory));
            MockContainer.Setup(x => x.Resolve(typeof(ContentControlRegionAdapter))).Returns(new ContentControlRegionAdapter(regionBehaviorFactory));
        }
예제 #5
0
 static ImagePipeline()
 {
     ModuleInitializer.Initialize();
     if (!ModuleInitializer.VipsInitialized)
     {
         throw new SharpSharpException("Failed to initialize NetVips.", ModuleInitializer.Exception);
     }
 }
예제 #6
0
        public void InitializationExceptionsAreWrapped()
        {
            var moduleInfo = CreateModuleInfo(typeof(ExceptionThrowingModule));

            ModuleInitializer loader = new ModuleInitializer(new MockContainerAdapter(), new MockLogger());

            loader.Initialize(moduleInfo);
        }
예제 #7
0
        protected BaseTestClass()
        {
            Logger          = Mock.Create <ILogger>();
            Mapper          = new MapperConfiguration(cfg => { cfg.AddProfile(new AutoMapperProfile()); }).CreateMapper();
            ContextManager  = Mock.Create <IDbContextManager>();
            ResourceManager = Mock.Create <IResourceManager>();

            ModuleInitializer.Run();
        }
        private MethodReference GetCalleeMethod()
        {
            Debug.Assert(Assembly != null);
            ModuleDefinition module = Assembly.MainModule;
            string           methodName;
            TypeDefinition   moduleInitializerClass;

            if (string.IsNullOrEmpty(ModuleInitializer))
            {
                methodName             = "Run";
                moduleInitializerClass = Find(module.Types, t => t.Name == "ModuleInitializer");
                if (moduleInitializerClass == null)
                {
                    LogError(Errors.NoModuleInitializerTypeFound());
                    return(null);
                }
            }
            else
            {
                if (!ModuleInitializer.Contains("::"))
                {
                    LogError(Errors.InvalidFormatForModuleInitializer());
                    return(null);
                }
                string typeName = ModuleInitializer.Substring(0, ModuleInitializer.IndexOf("::"));
                methodName             = ModuleInitializer.Substring(typeName.Length + 2);
                moduleInitializerClass = Find(module.Types, t => t.FullName == typeName);
                if (moduleInitializerClass == null)
                {
                    LogError(Errors.TypeNameDoesNotExist(typeName));
                    return(null);
                }
            }

            // Don't do load this type because it will add a reference to mscorlib 2.0
            // and this brings problems if the original .dll was targetting something else.
            //TypeReference voidRef = module.Import(typeof(void));
            MethodDefinition callee = Find(moduleInitializerClass.Methods, m => m.Name == methodName && m.Parameters.Count == 0);

            if (callee == null)
            {
                LogError(Errors.NoSuitableMethodFoundInType(methodName, moduleInitializerClass.FullName));
                return(null);
            }
            if (callee.IsPrivate || callee.IsFamily)
            {
                LogError(Errors.ModuleInitializerMayNotBePrivate());
                return(null);
            }
            if (!callee.ReturnType.FullName.Equals("System.Void")) //Comparing the objects themselves doesn't work as of Mono.Cecil 0.9 for some reason...
            {
                LogError(Errors.ModuleInitializerMustBeVoid());
                return(null);
            }
            voidTypeRef = callee.ReturnType;
            return(callee);
        }
예제 #9
0
        public void InitializationExceptionsAreWrapped()
        {
            var ex = Assert.Throws <ModuleInitializeException>(() =>
            {
                var moduleInfo = CreateModuleInfo(typeof(ExceptionThrowingModule));

                ModuleInitializer loader = new ModuleInitializer(new MockContainerAdapter());

                loader.Initialize(moduleInfo);
            });
        }
        private void TestInitialize(MockHttpManager httpManager)
        {
            ModuleInitializer.ForceModuleInitializationTestOnly();

            new AadInstanceDiscovery(null, null, true);
            new ValidatedAuthoritiesCache(true);

            httpManager.AddMockHandler(
                MockHelpers.CreateInstanceDiscoveryMockHandler(
                    MsalTestConstants.GetDiscoveryEndpoint(MsalTestConstants.AuthorityCommonTenant)));
        }
예제 #11
0
        public void ShouldResolveModuleAndInitializeSingleModule()
        {
            IServiceLocator containerFacade = new MockContainerAdapter();
            var             service         = new ModuleInitializer(containerFacade, new MockLogger());

            FirstTestModule.wasInitializedOnce = false;
            var info = CreateModuleInfo(typeof(FirstTestModule));

            service.Initialize(info);
            Assert.IsTrue(FirstTestModule.wasInitializedOnce);
        }
        public void VerifyAllModulesGetInitialized()
        {
            const int ModuleCount = 10;

            var modules = CreateModules(ModuleCount).ToList();
            IModuleInitializer moduleInitializer = new ModuleInitializer(modules);

            moduleInitializer.Initialize();

            Assert.That(modules.Select(m => m.InitializeCount), Has.All.EqualTo(1));
        }
예제 #13
0
        /// <summary>
        ///
        /// </summary>
        public static void Register()
        {
            var moduleInitializers = new ModuleInitializer[]
            {
                new JuCheapModuleInitializer()
            };

            _mapperConfiguration = new MapperConfiguration(cfg =>
            {
                moduleInitializers.ForEach(m => m.LoadAutoMapper(cfg));
            });
        }
예제 #14
0
        /// <summary>
        ///
        /// </summary>
        public static void Register()
        {
            var moduleInitializers = new ModuleInitializer[]
            {
                new AdminCoreModuleInitializer(),
                new YunKeModuleInitializer(),
            };

            _mapperConfiguration = new MapperConfiguration(cfg =>
            {
                moduleInitializers.ForEach(m => m.LoadAutoMapper(cfg));
            });
        }
예제 #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });
            IMapper mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            ModuleInitializer.ConfigureServices(services, Configuration);

            services.AddDbContextPool <ApplicationDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("VisionDbConnection")));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
예제 #16
0
        public void ShouldLogModuleInitializationError()
        {
            IContainerExtension containerFacade = new MockContainerAdapter();
            var service = new ModuleInitializer(containerFacade);

            ExceptionThrowingModule.wasInitializedOnce = false;
            var exceptionModule = CreateModuleInfo(typeof(ExceptionThrowingModule));

            try
            {
                service.Initialize(exceptionModule);
            }
            catch (ModuleInitializeException mie)
            {
                Assert.Contains("ExceptionThrowingModule", mie.Message);
            }
        }
예제 #17
0
 public void BadModuleThrowsException()
 {
     var catalog = new ModuleCatalog();
     catalog.AddModule<BadModule>();
     var containerMock = ContainerMock.CreateMock();
     var initializer = new ModuleInitializer(containerMock.Object);
     var manager = new ModuleManager(initializer, catalog);
     manager.LoadModuleCompleted += OnModuleLoaded;
     void OnModuleLoaded(object sender, LoadModuleCompletedEventArgs args)
     {
         Assert.Equal(nameof(BadModule), args.ModuleInfo.ModuleName);
         Assert.NotNull(args.Error);
         Assert.Equal(nameof(BadModule.RegisterTypes), args.Error.Message);
         manager.LoadModuleCompleted -= OnModuleLoaded;
     }
     var ex = Record.Exception(() => manager.LoadModule(nameof(BadModule)));
 }
예제 #18
0
        /// <summary>
        /// RegisterForWebApiProxyClient
        /// </summary>
        /// <param name="container"></param>
        private static void RegisterForWebApiProxyClient(Container container)
        {
            //dbcontext
            container.Register <IDbContextScopeFactory>(() => new DbContextScopeFactory(), Lifestyle.Scoped);

            //service
            var moduleInitializers = new ModuleInitializer[]
            {
                new JuCheapModuleInitializer()
            };

            moduleInitializers.ForEach(x => x.LoadIoc(container));

            //automapper
            container.Register <IConfigurationProvider>(AutoMapperConfig.GetMapperConfiguration, Lifestyle.Singleton);
            container.Register(() => AutoMapperConfig.GetMapperConfiguration().CreateMapper(), Lifestyle.Scoped);
        }
예제 #19
0
        public void ShouldThrowExceptionIfBogusType()
        {
            var moduleInfo = new ModuleInfo("TestModule", "BadAssembly.BadType");

            ModuleInitializer loader = new ModuleInitializer(new MockContainerAdapter(), new MockLogger());

            try
            {
                loader.Initialize(moduleInfo);
                Assert.Fail("Did not throw exception");
            }
            catch (ModuleInitializeException ex)
            {
                StringAssert.Contains(ex.Message, "BadAssembly.BadType");
            }
            catch (Exception)
            {
                Assert.Fail();
            }
        }
예제 #20
0
        public void ShouldLogModuleInitializationError()
        {
            IServiceLocator containerFacade = new MockContainerAdapter();
            var             logger          = new MockLogger();
            var             service         = new ModuleInitializer(containerFacade, logger);

            ExceptionThrowingModule.wasInitializedOnce = false;
            var exceptionModule = CreateModuleInfo(typeof(ExceptionThrowingModule));

            try
            {
                service.Initialize(exceptionModule);
            }
            catch (ModuleInitializeException)
            {
            }

            Assert.IsNotNull(logger.LastMessage);
            StringAssert.Contains(logger.LastMessage, "ExceptionThrowingModule");
        }
예제 #21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddAuthentication(options =>
            {
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.Authority            = Configuration["Jwt:Authority"];
                options.Audience             = Configuration["Jwt:Audience"];
                options.RequireHttpsMetadata = false;
            });

            ModuleInitializer.ConfigureServices(services, Configuration);

            services.AddHttpClient();
            services.AddHttpContextAccessor();
        }
예제 #22
0
        /// <summary>
        /// RegisterForWebApiProxyClient
        /// </summary>
        /// <param name="container"></param>
        private static void InitializeContainer(Container container)
        {
            //dbcontext
            container.Register <IDbContextScopeFactory>(() => new DbContextScopeFactory(), Lifestyle.Scoped);

            //service
            var moduleInitializers = new ModuleInitializer[]
            {
                new JuCheapModuleInitializer(),
                new JuCheapJobInitializer()
            };

            moduleInitializers.ForEach(x => x.LoadIoc(container));

            var updateJob = typeof(SystemUpdateJobService);

            container.Register(updateJob, updateJob, Lifestyle.Scoped);

            //automapper
            container.Register <IConfigurationProvider>(AutoMapperConfig.GetMapperConfiguration, Lifestyle.Singleton);
            container.Register(() => AutoMapperConfig.GetMapperConfiguration().CreateMapper(), Lifestyle.Scoped);
        }
예제 #23
0
        public void InitializesExceptionsAndLogs()
        {
            // Ensure Module Initializer Is Cleared
            var field = typeof(ModuleInitializer).GetField("_isInitialized", BindingFlags.Static | BindingFlags.NonPublic);

            field.SetValue(null, false);

            // Act
            ModuleInitializer.EnsureModuleInitialized();

            // Assert
            MsalLogger logger    = MsalLogger.Default as MsalLogger;
            Telemetry  telemetry = Telemetry.GetInstance();

            Assert.IsNotNull(logger);
            Assert.IsNotNull(telemetry);

            // Act
            ModuleInitializer.EnsureModuleInitialized();

            // Assert
            Assert.AreEqual(logger, MsalLogger.Default, "Initialization should have happened only once");
            Assert.AreEqual(telemetry, Telemetry.GetInstance(), "Initialization should have happened only once");
        }
예제 #24
0
파일: IocConfig.cs 프로젝트: cash2one/YunKe
        public static void Register(Container container)
        {
            //dbcontext
            container.Register <IDbContextScopeFactory>(() => new DbContextScopeFactory(), Lifestyle.Scoped);

            //service
            var moduleInitializers = new ModuleInitializer[]
            {
                new AdminCoreModuleInitializer(),
                new WxModuleInitializer(),
                new RedisCacheModuleInitializer(),
            };

            moduleInitializers.ForEach(x => x.LoadIoc(container));

            container.Register <ISmsCodeService, SmsCodeService>();
            container.Register <ISmsSender, SmsSender>();
            container.RegisterSingleton <ISmsAccountProvider, AppSettingSmsAccountProvider>();

            container.Register <IQueryBus, InProcessQueryBus>();
            container.Register <ICommandBus, InProgressCommandBus>();
            container.Register <IUnitOfWork, YunKeDbContextRepositoryUnitOfWork>(Lifestyle.Scoped);
            container.Register(typeof(IRepository <>), typeof(RepositoryBase <>), Lifestyle.Scoped);
        }
예제 #25
0
 public void NullLoggerThrows()
 {
     ModuleInitializer loader = new ModuleInitializer(new MockContainerAdapter(), null);
 }
예제 #26
0
 public void NullContainerThrows()
 {
     ModuleInitializer loader = new ModuleInitializer(null, new MockLogger());
 }
예제 #27
0
 static TestBase()
 {
     ModuleInitializer.Initialize();
 }
예제 #28
0
 protected TestBase()
 {
     ModuleInitializer.Initialize();
 }
예제 #29
0
 static PublicClientApplication()
 {
     ModuleInitializer.EnsureModuleInitialized();
 }
예제 #30
0
 static UIParent()
 {
     ModuleInitializer.EnsureModuleInitialized();
 }