private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            var websiteConfigurations = (IWebsiteConfigurations)ConfigurationManager.GetSection("websiteConfiguration");
            container.RegisterInstance(typeof(IWebsiteConfigurations), websiteConfigurations);
            container.RegisterType<IConnectionstringArgumentsMapper, SqlServerConnectionstringArgumentsMapper>();
            container.RegisterType<ISchemaReader, SchemaReader>();

            container.RegisterType<IConnectionstringBuilder, ConnectionstringBuilder.ConnectionstringBuilder>();
            container.RegisterType<IConnectionstringBuilderFactory, ConnectionstringBuilderFactory>();
            container.RegisterType<IConnectionstringArgumentsMapperFactory, ConnectionstringArgumentsMapperFactory>();

            container.RegisterType<IForeignKeyMapper, ForeignKeyMapper>();
            container.RegisterType<IColumnMapper, ColumnMapper>();
            container.RegisterType<IIndexMapper, IndexMapper>();
            container.RegisterType<IUserMapper, UserMapper>();

            container.RegisterType<IAccountService, AccountService>();

            var store = InitalizeRavenDbDocumentStore(websiteConfigurations);

            container.RegisterInstance(store);

            return container;
        }
 protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
 {
     IUnityContainer container = new UnityContainer();
     //
     // Archivo Config de la aplicación.
     //  Aquí se encuentra la definición de los servicios a tratar por ServiceHost
     //
     ((UnityConfigurationSection)ConfigurationManager.GetSection("unity")).Configure(container);
     //((UnityConfigurationSection)ConfigurationManager.GetSection("unity")).Configure(container.CreateChildContainer());
     container.RegisterInstance<IUnityContainer>(container);
     container.RegisterType<IServiceBehavior, UnityServiceBehavior>();
     container.RegisterInstance<Type>("service-type",  serviceType);
     container.RegisterType<IInstanceProvider, UnityInstanceProvider>
         (
             new InjectionConstructor
                 (
                     new ResolvedParameter<IUnityContainer>(),
                     new ResolvedParameter<Type>("service-type")
                 )
         );
     container.RegisterType<ServiceHost, UnityServiceHost>
         (
             new InjectionConstructor
                 (
                     new ResolvedParameter<IServiceBehavior>(),
                     new ResolvedParameter<Type>("service-type"),
                     baseAddresses
                 )
         );
     ServiceHost instance = container.Resolve<ServiceHost>();
     //container.d
     return instance;
 }
Beispiel #3
0
        public MainForm()
        {
            InitializeComponent();

            var container = new UnityContainer();
            container.RegisterInstance(container);
            ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));

            string exePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), HostMetadata.PortalServiceExe);
            serviceManager = new ServiceManager(HostMetadata.PortalServiceName, exePath);

            configuration = new ConfigurationManager(HostMetadata.PortalApp, Environment.SpecialFolder.CommonApplicationData);
            container.RegisterInstance(configuration);

            settings = configuration.GetSection<PortalSettings>(PortalSettings.SectionKey);
            container.RegisterInstance(settings);

            portalSettingsBindingSource.DataSource = settings;

            loginSettings = configuration.GetSection<LoginSettings>(LoginSettings.SectionKey);
            container.RegisterInstance(loginSettings);

            loginSettingsControl.Settings = loginSettings;

            portalServiceSettings = configuration.GetSection<PortalServiceSettings>(PortalServiceSettings.SectionKey);
            container.RegisterInstance(portalServiceSettings);

            portalServiceSettingsBindingSource.DataSource = portalServiceSettings;

            loginSettingsControl.UserRole = UserRole.Administrator;
        }
        static void Main(string[] args)
        {
            UnityContainer container = new UnityContainer();
            container.RegisterInstance<IServiceLocator>(new UnityServiceLocatorAdapter(container));

            container.RegisterType<IModuleInitializer, ModuleInitializer>();

            TextLogger logger = new TextLogger();
            container.RegisterInstance<ILoggerFacade>(logger);

            IEventAggregator eventAggregator = new EventAggregator();
            container.RegisterInstance<IEventAggregator>(eventAggregator);

            ModuleCatalog catalog = new ModuleCatalog();
            //catalog.AddModule(typeof(RFID.RFIDModule));
            catalog.AddModule(typeof(BookInformation.BookInformationModule));
            catalog.AddModule(typeof(BookLocation.BookLocationModule));
            container.RegisterInstance<IModuleCatalog>(catalog);

            container.RegisterType<IModuleManager, ModuleManager>();
            IModuleManager manager = container.Resolve<IModuleManager>();
            manager.Run();
            //测试RFID服务模块的功能
            //RFIDUnitTest.testRFID(container);
            /******/
            //测试串口服务的功能
            //SerialUnitTest.testSerial(container);
            //测试数据库功能
            DatabaseUnitTest.testAllDatabase(container);
        }
Beispiel #5
0
        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings["WhaConnection"];

            string providerName = connectionStringSettings.ProviderName;
            string connectionString = connectionStringSettings.ConnectionString;

            DbProviderFactory databaseProviderFactory = DbProviderFactories.GetFactory(providerName);

            container.RegisterInstance(databaseProviderFactory);

            // e.g. container.RegisterType<ITestService, TestService>();
            //container.Register(c => new KiggDbFactory(c.Resolve<DbProviderFactory>(), connectionString)).As<IKiggDbFactory>().InstancePerLifetimeScope();
            //container.Register(c => new QueryFactory(c.Resolve<IKiggDbFactory>(), true)).As<IQueryFactory>().SingleInstance();

            container.RegisterInstance<IWhaDbFactory>(new WhaDbFactory(databaseProviderFactory, connectionString));//.As<IWhaDbFactory>().InstancePerLifetimeScope();

            //container.RegisterType<IWhaDbFactory, WhaDbFactory>();
            container.RegisterType<IQueryFactory, QueryFactory>();

            container.RegisterType<ITourRepository, TourRepository>();
            container.RegisterType<ILocationRepository, LocationRepository>();
            return container;
        }
Beispiel #6
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            
            var container = new UnityContainer();
            container.RegisterType<IStoreService, StoreService>();
            container.RegisterType<IController, StoreController>("Store");

            var factory = new UnityControllerFactory(container);
            ControllerBuilder.Current.SetControllerFactory(factory);

            IDependencyResolver resolver = DependencyResolver.Current;

            // You could implement another IMessageService, maybe a dynamic one
            container.RegisterInstance<IMessageService>(new MessageService { 
                Message = "You are welcome to our Web Camps Training Kit!",
                ImageUrl = "/Content/Images/logo-webcamps.png"    
            });
            container.RegisterType<IViewPageActivator, CustomViewPageActivator>(new InjectionConstructor(container));

            container.RegisterInstance<IFilterProvider>("FilterProvider", new FilterProvider(container));
            container.RegisterInstance<IActionFilter>("LogActionFilter", new TraceActionFilter());

            IDependencyResolver newResolver = new UnityDependencyResolver(container, resolver);

            DependencyResolver.SetResolver(newResolver);
        }
Beispiel #7
0
        public void ResolveAllOnlyReturnsInterfaceRegistrations()
        {
            ITest iTest;

            ATest objA = new ATest();
            BTest objB = new BTest();
            CTest objC = new CTest();

            objA.Strtest = "Hi";

            UnityContainer uc1 = new UnityContainer();

            uc1.RegisterType<ITest, ATest>();

            iTest = objA;
            uc1.RegisterInstance("ATest", iTest);
            iTest = objB;
            uc1.RegisterInstance("BTest", iTest);
            iTest = objC;
            uc1.RegisterInstance("CTest", iTest);

            List<ATest> list = new List<ATest>(uc1.ResolveAll<ATest>());
            List<ITest> list3 = new List<ITest>(uc1.ResolveAll<ITest>());

            Assert.AreEqual(0, list.Count);
            Assert.AreEqual(3, list3.Count);
        }
Beispiel #8
0
        private IUnityContainer BuildUpContainer()
        {
            var container =  new UnityContainer();

            container.RegisterType<IUdpClientServer, UdpClientServer>(new ContainerControlledLifetimeManager());

            var serverAddress = ConfigurationManager.AppSettings.Get("ServerAddress");
            var serverPort = int.Parse(ConfigurationManager.AppSettings.Get("ServerPort"));
            container.RegisterInstance<IChannelConfig>(ChannelNames.Server, new ChannelConfig { Address = serverAddress, Port = serverPort }, new ContainerControlledLifetimeManager());
            container.RegisterType<ICommunicationChannel, UdpCommunicationChannel>(
                ChannelNames.Server,
                new ContainerControlledLifetimeManager(),
                new InjectionFactory(c => new UdpCommunicationChannel(c.Resolve<IUdpClientServer>(), c.Resolve<IChannelConfig>(ChannelNames.Server))));

            var clientAddress = ConfigurationManager.AppSettings.Get("ClientAddress");
            var clientPort = int.Parse(ConfigurationManager.AppSettings.Get("ClientPort"));
            container.RegisterInstance<IChannelConfig>(ChannelNames.Client, new ChannelConfig { Address = clientAddress, Port = clientPort }, new ContainerControlledLifetimeManager());
            container.RegisterType<ICommunicationChannel, UdpCommunicationChannel>(
                ChannelNames.Client,
                new ContainerControlledLifetimeManager(),
                new InjectionFactory(c => new UdpCommunicationChannel(c.Resolve<IUdpClientServer>(), c.Resolve<IChannelConfig>(ChannelNames.Client))));

            container.RegisterType(typeof(IService<,>), typeof(Service<,>), new ContainerControlledLifetimeManager());
            container.RegisterType(typeof(ITopic<>), typeof(Topic<>), new ContainerControlledLifetimeManager());

            var ch = container.Resolve<ICommunicationChannel>(ChannelNames.Client);
            ch.SendMessage(new UserQuery("xxx"));

            container.RegisterType(typeof(IRepoWatch), typeof(RepoWatch), new ContainerControlledLifetimeManager());
            container.RegisterType<RepoHub>(new InjectionFactory(c => new RepoHub(c.Resolve<IRepoWatch>())));

            return container;
        }
        public static IUnityContainer CreateUnityContainer()
        {
            var container = new UnityContainer();
            container.RegisterType<IMediator, Mediator>();
            var types = AllClasses.FromAssemblies( typeof( Program ).Assembly );

            container.RegisterTypes(
                types,
                WithMappings.FromAllInterfaces,
                GetName,
                GetLifetimeManager,
                null,
                true );

            container.RegisterInstance<SingleInstanceFactory>( t =>
             {
                 var pipeline = container.Resolve(
                     typeof( MediatorPipeline<,> ).MakeGenericType( t.GetGenericArguments() )
                 );

                 return pipeline;

             } );
            container.RegisterInstance<MultiInstanceFactory>( t => container.ResolveAll( t ) );

            return container;
        }
Beispiel #10
0
        protected override void OnStart(string[] args)
        {
            logger.Info("Starting service...");

            try
            {
                container = new UnityContainer();
                container.RegisterInstance(container);
                ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));

                configuration = new ConfigurationManager(HostMetadata.ServerApp, SpecialFolder.CommonApplicationData);
                container.RegisterInstance(configuration);

                settings = configuration.GetSection<ServerSettings>(ServerSettings.SectionKey);
                container.RegisterInstance(settings);

                templateServiceSettings = configuration.GetSection<TemplateServiceSettings>(TemplateServiceSettings.SectionKey);
                container.RegisterInstance(templateServiceSettings);

                var culture = settings.Language.GetCulture();
                Thread.CurrentThread.CurrentCulture = culture;
                CultureInfo.DefaultThreadCurrentCulture = culture;

                server = new ServerInstance(settings);
                server.Start();

                logger.Info("Service started");
            }
            catch (Exception e)
            {
                logger.Error(e);
                throw;
            }
        }
Beispiel #11
0
        public void CanPut()
        {
            var mockConfiguration = new Mock<IConfigurationManager>();

            var systemConfiguration = new Mock<IConfiguration>();
            var applicationConfiguration = new Mock<IConfiguration>();
        
            mockConfiguration.Setup(ctx => ctx.ApplicationConfiguration).Returns(applicationConfiguration.Object);
            mockConfiguration.Setup(ctx => ctx.SystemConfiguration).Returns(systemConfiguration.Object);

            
            _container = new UnityContainer();
            var mock = new Mock<IBlobStore>();
           
            _container.RegisterInstance(mock.Object);

            _container.RegisterInstance(mockConfiguration.Object);
            var test = new MockBlobData();
          
           

            mock.Setup(m => new BaseBlobStore(Storage.BlobStore.GetBlobClient(mockConfiguration.Object)).Put(test));

            mock.Setup(m => new Storage.BlobStore(mockConfiguration.Object).Put(_context, streamBlobData));
            var mock2 = new Mock<BaseBlobStore>();
            mock2.Setup(m =>  new BaseBlobStore(Storage.BlobStore.GetBlobClient(mockConfiguration.Object)).Put(test));

            mock2.Verify();
            
            mock.Verify();

        }
        public static void BuildUp(Frame frame)
        {
            Debug.WriteLine("Bootstrapping begins");

            var navigationService = new FrameNavigationService(frame);
            navigationService.RegisterView("MainPage", typeof(MainPage));
            navigationService.RegisterView("SecondPage", typeof(SecondPage));
            navigationService.RegisterView("GroupedItemsPage", typeof(GroupedItemsPage));

            var x = typeof(MainPage); // Required to force JIT of Pages.dll

            var container = new UnityContainer();

            // Services
            container.RegisterInstance<INavigationService>(navigationService);

            container.RegisterType<IDialogService, DialogService>();
            container.RegisterType<IProtectionService, DPAPIProtectionService>();
            container.RegisterType<ISettingsService, SettingsService>(new InjectionConstructor(SettingsPolicy.Roaming));
            container.RegisterType<ISocialService, FacebookService>();
            container.RegisterType<ISerializerService, XmlSerializerService>();
            container.RegisterType<IStorageService, LocalFolderStorageService>();
            container.RegisterType<IDeviceSpecificsService, DeviceSpecificsService>();

            // ViewModels
            container.RegisterType<IMainViewModel, MainViewModel>();

            // Register container for ViewModelLocator
            var containerWrapper = new UnityContainerWrapper(container);
            container.RegisterInstance<IContainer>(containerWrapper);

            new ServiceLocator(containerWrapper);

            Debug.WriteLine("Bootstrapping ends");
        }
Beispiel #13
0
 public TestModule()
 {
     Container = new UnityContainer();
     Container.RegisterInstance<ILoginDialog>(new Mock<ILoginDialog>().Object);
     Container.RegisterInstance<ISSOConfiguration>(GetSSOConfigurationMock().Object);
     Container.RegisterInstance<ISSOManager>(new Mock<ISSOManager>().Object);
 }
Beispiel #14
0
        public static void Register(HttpConfiguration config)
        {
           var  container = new UnityContainer();

            var applicationDbContext = new ApplicationDatabaseContext();
            var userStore = new UserStore<Person>(applicationDbContext);
            container.RegisterInstance(
                typeof(ApplicationDatabaseContext), applicationDbContext);

            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies()
                    .Where(
                        type =>
                        (typeof(IManager).IsAssignableFrom(type) || typeof(IStore).IsAssignableFrom(type))
                        && !type.IsAbstract && !type.IsInterface),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.PerResolve);
            container.RegisterType<IEmailManager, EmailManager>();
            var userManager = AuthConfig.ConfigureUserManager(userStore, null);
            container.RegisterInstance(typeof(UserManager<Person>), userManager);
            container.RegisterInstance(typeof(IUserStore<Person>), userStore);
            // Web API configuration and services
            config.DependencyResolver = new UnityDependencyResolver(container);

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
        partial void OnCreateContainer(UnityContainer container)
        {
            var metadata = container.Resolve<IMetadataProvider>();
            var serializer = container.Resolve<ITextSerializer>();

            // blob
            var blobStorageAccount = CloudStorageAccount.Parse(azureSettings.BlobStorage.ConnectionString);
            container.RegisterInstance<IBlobStorage>(new SqlBlobStorage("BlobStorage"));

            var commandBus = new CommandBus(new TopicSender(azureSettings.ServiceBus, Topics.Commands.Path), metadata, serializer);
            var topicSender = new TopicSender(azureSettings.ServiceBus, Topics.Events.Path);
            container.RegisterInstance<IMessageSender>(topicSender);
            var eventBus = new EventBus(topicSender, metadata, serializer);

            var commandProcessor =
                new CommandProcessor(new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, "all", false, new SubscriptionReceiverInstrumentation("all", this.instrumentationEnabled)), serializer);

            container.RegisterInstance<ICommandBus>(commandBus);

            container.RegisterInstance<IEventBus>(eventBus);
            container.RegisterInstance<IProcessor>("CommandProcessor", commandProcessor);

            RegisterRepository(container);
            RegisterEventProcessors(container);
            RegisterCommandHandlers(container, commandProcessor);
        }
Beispiel #16
0
        protected override void Configure()
        {
            container = new UnityContainer();
            container.RegisterInstance<IWindowManager>(new WindowManager());
            container.RegisterInstance<IEventAggregator>(new EventAggregator());

        }
Beispiel #17
0
        private static void configure(UnityContainer container)
        {
            container.RegisterInstance<IUnityContainer>(container);

            //MoneyManager.WebApi
            container.RegisterType<ICategoryController, CategoryController>();
            container.RegisterType<IExpenseController, ExpenseController>();
            container.RegisterType<IIncomeController, IncomeController>();
            container.RegisterType<ICategoryService, CategoryService>();
            container.RegisterType<IExpenseService, ExpenseService>();
            container.RegisterType<IIncomeService, IncomeService>();
            container.RegisterType<IMapperService, MapperService>();

            //MoneyManager.DataAccess
            container.RegisterInstance<DAC.Services.IMapperService>(new DAC.Services.MapperService());
            container.RegisterType<IDbContext, MoneyManagerContext>();
            container.RegisterType<ICategoryRepository, CategoryRepository>();
            container.RegisterType<IExpenseRepository, ExpenseRepository>();
            container.RegisterType<IIncomeRepository, IncomeRepository>();

            //MoneyManager.Business
            container.RegisterType<ICategoryBusiness, CategoryBusiness>();
            container.RegisterType<IExpenseBusiness, ExpenseBusiness>();
            container.RegisterType<IIncomeBusiness, IncomeBusiness>();
            container.RegisterType<IUnitOfWorkFactory, UnitOfWorkFactory>();
            container.RegisterType<IUnitOfWork, UnitOfWork>();
            container.RegisterType<IDateHelper, DateHelper>();
        }
Beispiel #18
0
      private static IUnityContainer ConfigureContainer(IServiceProvider package, ServiceLocatorOptions options)
      {
         if (package == null)
            throw new ArgumentNullException(nameof(package), $"{nameof(package)} is null.");

         IUnityContainer container = new UnityContainer();
         container.AddExtension(new ServiceProviderUnityExtension(package, options));

         container.RegisterType<IToolkit, TookitImpl>(new ContainerControlledLifetimeManager());
         container.RegisterTypes(new SolutionExplorerNodeFactoryRegistrationConvention());
         container.RegisterType<IEnumerable<ISolutionExplorerNodeFactory>, ISolutionExplorerNodeFactory[]>();
         container.RegisterType<ISolutionExplorerNodeFactory, GlobalSolutionExplorerNodeFactory>();

         container.RegisterType<ISolutionExplorer, SolutionExplorer>();
         container.RegisterType<IOutputWindow, OutputWindow>(new ContainerControlledLifetimeManager());
         container.RegisterType<IDialogService, DialogService>(new ContainerControlledLifetimeManager());

         container.RegisterType<IEnumerable<ICommandImplementation>, ICommandImplementation[]>();

         container.RegisterInstance<IServiceProvider>(package);

         container.RegisterType<ICommandManager, CommandManager>(new ContainerControlledLifetimeManager());

         UnityServiceLocator serviceLocator = new UnityServiceLocator(container);
         container.RegisterInstance<IServiceLocator>(serviceLocator);

         if (!ServiceLocator.IsLocationProviderSet)
            ServiceLocator.SetLocatorProvider(() => serviceLocator);

         return container;
      }
Beispiel #19
0
        public override void Configure(Container container)
        {
            var unityContainer = new UnityContainer()
              .AddNewExtension<BuildTracking>()
              .AddNewExtension<LogCreation>();

            var userRepository = new InMemoryAuthRepository();

            this.Plugins.Add(new AuthFeature(() => new AuthUserSession(),
              new IAuthProvider[] { new BasicAuthProvider()}));

            this.Plugins.Add(new RegistrationFeature());

            unityContainer.RegisterInstance<ICacheClient>(new MemoryCacheClient());
            unityContainer.RegisterInstance<IUserAuthRepository>(userRepository);

            unityContainer.RegisterInstance<IDbConnectionFactory>(new OrmLiteConnectionFactory("~/Database/SmartDom.db".MapServerPath(),
                SqliteOrmLiteDialectProvider.Instance));

            unityContainer.RegisterType<IOrmWrapper, OrmWrapper>();
            unityContainer.RegisterType<IConfigurationRepository, AppConfigRepository>();
            unityContainer.RegisterType<MediaAdapterAbstractFactory<SerialPort>, SerialPortAdapterFactory>(new ContainerControlledLifetimeManager());
            unityContainer.RegisterType<ModbusMasterAbstractFactory<SerialPort>, RtuSerialModbusMasterFactory>(new ContainerControlledLifetimeManager());
            unityContainer.RegisterType<IGenericRepository<Device>, DeviceDbRepository>(new ContainerControlledLifetimeManager(),
                new InjectionMethod("Initialize"));
            unityContainer.RegisterType<IDeviceAccessLayer, SerialAccessLayer>(new ContainerControlledLifetimeManager());
            unityContainer.RegisterType<IMessageDecoder, MessageDecoder>();
            unityContainer.RegisterType<IDeviceManager, DeviceManager>();

            var unityAdapter = new UnityContainerAdapter(unityContainer);
            container.Adapter = unityAdapter;

            AddUser(userRepository);
        }
Beispiel #20
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var container = new UnityContainer();

            container.RegisterType<IUdpClientServer, UdpClientServer>(new ContainerControlledLifetimeManager());

            var serverAddress = ConfigurationManager.AppSettings.Get("ServerAddress");
            var serverPort = int.Parse(ConfigurationManager.AppSettings.Get("ServerPort"));
            container.RegisterInstance<IChannelConfig>(ChannelNames.Server, new ChannelConfig { Address = serverAddress, Port = serverPort }, new ContainerControlledLifetimeManager());
            container.RegisterType<ICommunicationChannel, UdpCommunicationChannel>(
                ChannelNames.Server,
                new ContainerControlledLifetimeManager(),
                new InjectionFactory(c => new UdpCommunicationChannel(c.Resolve<IUdpClientServer>(), c.Resolve<IChannelConfig>(ChannelNames.Server))));

            var clientAddress = ConfigurationManager.AppSettings.Get("ClientAddress");
            var clientPort = int.Parse(ConfigurationManager.AppSettings.Get("ClientPort"));
            container.RegisterInstance<IChannelConfig>(ChannelNames.Client, new ChannelConfig { Address = clientAddress, Port = clientPort }, new ContainerControlledLifetimeManager());
            container.RegisterType<ICommunicationChannel, UdpCommunicationChannel>(
                ChannelNames.Client,
                new ContainerControlledLifetimeManager(),
                new InjectionFactory(c => new UdpCommunicationChannel(c.Resolve<IUdpClientServer>(), c.Resolve<IChannelConfig>(ChannelNames.Client))));

            container.RegisterType(typeof(IService<,>), typeof(Service<,>), new ContainerControlledLifetimeManager());
            container.RegisterType(typeof(ITopic<>), typeof(Topic<>), new ContainerControlledLifetimeManager());

            var ch = container.Resolve<ICommunicationChannel>(ChannelNames.Client);
            ch.SendMessage(new UserQuery("xxx"));

            container.RegisterType<MainWindowViewModel, MainWindowViewModel>(new ContainerControlledLifetimeManager());
            container.RegisterType<MainWindow>(new ContainerControlledLifetimeManager());

            container.Resolve<MainWindow>().Show();
        }
Beispiel #21
0
        public App()
        {
            try
            {
                IUnityContainer unityContainer = new UnityContainer();

                var connectionString = System.Configuration.ConfigurationSettings.AppSettings.Get("webService");
                IWebservice webService = new Webservice(connectionString);

                EventAggregator eventAggregator = new EventAggregator();
                unityContainer.RegisterInstance<IEventAggregator>(eventAggregator);
                unityContainer.RegisterInstance<IWebservice>(webService);

                IMessaging emailMessenger = new EmailMessaging();
                unityContainer.RegisterInstance<IMessaging>(emailMessenger);

                var regionManager = new RegionManager();
                regionManager.Regions.Add(new Region() { Name = "MainContentRegion" });
                unityContainer.RegisterInstance<IRegionManager>(regionManager);

                ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(unityContainer));

            }
            catch (Exception ex)
            {
                logger.Error("Error in app constructor", ex);
            }
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            _container = new UnityContainer();
            _container.RegisterInstance<IUnityContainer>(_container);
            var locator = new UnityServiceLocator(_container);
            ServiceLocator.SetLocatorProvider(() => locator);

            _container.RegisterType<UserProvider>(new ContainerControlledLifetimeManager());

            _container.RegisterType<IChildViewModelManager, ChildViewModelManager>(new ContainerControlledLifetimeManager());
            _container.RegisterType<UserDetailsViewModel>(new ContainerControlledLifetimeManager());
            _container.RegisterType<UserListViewModel>(new ContainerControlledLifetimeManager());

            var mappingResolver = new MappingViewTypeResolver();
            mappingResolver.RegisterTypeMapping<UserDetailsView, UserDetailsViewModel>();
            mappingResolver.RegisterTypeMapping<UserListView, UserListViewModel>();
            mappingResolver.RegisterTypeMapping<UserDetailsWindow, UserDetailsWindowViewModel>();
            _container.RegisterInstance<IViewTypeResolver>(mappingResolver);
            var mainVM = _container.Resolve<MainWindowViewModel>();
            mainVM.Initialize();

            var mainWindow = new MainWindow();
            mainWindow.DataContext = mainVM;
            mainWindow.Show();
        }
Beispiel #23
0
        protected override void OnStart(string[] args)
        {
            logger.Info("Starting service...");

            try
            {
                container = new UnityContainer();
                container.RegisterInstance(container);
                ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));

                configuration = new ConfigurationManager(HostMetadata.PortalApp, SpecialFolder.CommonApplicationData);
                container.RegisterInstance(configuration);

                settings = configuration.GetSection<PortalSettings>(PortalSettings.SectionKey);
                container.RegisterInstance(settings);

                loginSettings = configuration.GetSection<LoginSettings>(LoginSettings.SectionKey);
                container.RegisterInstance(loginSettings);

                portalServiceSettings = configuration.GetSection<PortalServiceSettings>(PortalServiceSettings.SectionKey);
                container.RegisterInstance(portalServiceSettings);

                portal = new PortalInstance(settings, loginSettings);
                portal.Start();

                logger.Info("Service started");
            }
            catch (Exception e)
            {
                logger.Error(e);
                throw;
            }
        }
Beispiel #24
0
        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType<ITestService, TestService>();

            //Controller injection
            container.RegisterType<IEventService, EventService>();
            container.RegisterType<IController, EventsController>();

            //View injection
            container.RegisterInstance<IMessageService>(new MessageService
            {
                Message = "You are welcome to our Web Camps Training Kit!",
                ImageUrl = ""
            });
            container.RegisterType<IViewPageActivator, CustomViewPageActivator>(new InjectionConstructor(container));

            //Filter Injection
            container.RegisterInstance<IFilterProvider>("FilterProvider", new FilterProvider(container));
            container.RegisterInstance<IActionFilter>("LogActionFilter", new TraceActionFilter());

            RegisterTypes(container);

            return container;
        }
Beispiel #25
0
        public MainForm()
        {
            InitializeComponent();

            var container = new UnityContainer();
            container.RegisterInstance(container);
            ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));

            string exePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), HostMetadata.ServerServiceExe);
            serviceManager = new ServiceManager(HostMetadata.ServerServiceName, exePath);

            configuration = new ConfigurationManager(HostMetadata.ServerApp, Environment.SpecialFolder.CommonApplicationData);
            container.RegisterInstance(configuration);

            var commonApplicationData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            logger.Info(commonApplicationData);

            templateServiceSettings = configuration.GetSection<TemplateServiceSettings>(TemplateServiceSettings.SectionKey);
            container.RegisterInstance(templateServiceSettings);

            settings = configuration.GetSection<ServerSettings>(ServerSettings.SectionKey);
            container.RegisterInstance(settings);

            editDatabaseSettingsControl.Settings = settings.Database;
            languageControl.Initialize<Language>();
            languageControl.Select<Language>(settings.Language);
            licenseTypeControl.Initialize<ProductLicenceType>();
        }
        public static void Run(UnityContainer container)
        {
            container.RegisterType<StoreFrontController>();
            container.RegisterInstance(typeof(ILog), LogProvider.For<StoreService>(), new ContainerControlledLifetimeManager());
            container.RegisterType<AddOrderCommandHandler>();
            container.RegisterType<AddProductCommandHandler>();
            container.RegisterType<ChangeProductCommandHandler>();
            container.RegisterType<RemoveProductCommandHandler>();
            container.RegisterType<IProductsDAO, ProductsDAO>();

            var logger = container.Resolve<ILog>();
            var handlerFactory = new UnityHandlerFactory(container);

            var subscriberRegistry = new SubscriberRegistry();
            subscriberRegistry.Register<AddOrderCommand, AddOrderCommandHandler>();
            subscriberRegistry.Register<AddProductCommand, AddProductCommandHandler>();
            subscriberRegistry.Register<ChangeProductCommand, ChangeProductCommandHandler>();
            subscriberRegistry.Register<RemoveProductCommand, RemoveProductCommandHandler>();

            //create policies
            var retryPolicy = Policy
                .Handle<Exception>()
                .WaitAndRetry(new[]
                    {
                        TimeSpan.FromMilliseconds(50),
                        TimeSpan.FromMilliseconds(100),
                        TimeSpan.FromMilliseconds(150)
                    });

            var circuitBreakerPolicy = Policy
                .Handle<Exception>()
                .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                {CommandProcessor.RETRYPOLICY, retryPolicy},
                {CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy}
            };

            var messageMapperFactory = new UnityMessageMapperFactory(container);
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory);
            messageMapperRegistry.Register<AddOrderCommand, AddOrderCommandMessageMapper>();

            var gateway = new RmqMessageProducer(container.Resolve<ILog>());
            var dbPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase.Substring(8)), "App_Data\\MessageStore.sdf");

            IAmAMessageStore<Message> sqlMessageStore = new MsSqlMessageStore(new MsSqlMessageStoreConfiguration("DataSource=\"" + dbPath + "\"", "Messages", MsSqlMessageStoreConfiguration.DatabaseType.SqlCe), logger);

            var commandProcessor = CommandProcessorBuilder.With()
                    .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                    .Policies(policyRegistry)
                    .Logger(logger)
                    .TaskQueues(new MessagingConfiguration(sqlMessageStore, gateway, messageMapperRegistry))
                    .RequestContextFactory(new InMemoryRequestContextFactory())
                    .Build();

            container.RegisterInstance(typeof(IAmACommandProcessor), commandProcessor);
        }
        public static IUnityContainer Build(ICommandLineOptions options, ProductInformation productInformation)
        {
            var container = new UnityContainer();

            var targetMapper = new TargetMapper();
            targetMapper.LoadFromConfig(options.TargetMapFile);

            container.RegisterInstance<ICommandLineOptions>(options);
            container.RegisterInstance<ITargetMapper>(targetMapper);

            // For debug purposes, the FileOutputApiPortService helps as it serializes the request to json and opens it with the
            // default json handler. To use this service, uncomment the the next line and comment the one after that.
            //container.RegisterType<IApiPortService, FileOutputApiPortService>(new ContainerControlledLifetimeManager());
            container.RegisterInstance<IApiPortService>(new ApiPortService(options.ServiceEndpoint, productInformation));

            container.RegisterType<IEnumerable<IgnoreAssemblyInfo>, FileIgnoreAssemblyInfoList>(new ContainerControlledLifetimeManager());
            container.RegisterType<IDependencyFinder, ReflectionMetadataDependencyFinder>(new ContainerControlledLifetimeManager());
            container.RegisterType<IDependencyFilter, DotNetFrameworkFilter>(new ContainerControlledLifetimeManager());
            container.RegisterType<IReportGenerator, ReportGenerator>(new ContainerControlledLifetimeManager());
            container.RegisterType<ApiPortService>(new ContainerControlledLifetimeManager());
            container.RegisterType<IFileSystem, WindowsFileSystem>(new ContainerControlledLifetimeManager());
            container.RegisterType<IFileWriter, ReportFileWriter>(new ContainerControlledLifetimeManager());
            container.RegisterType<IRequestAnalyzer, RequestAnalyzer>(new ContainerControlledLifetimeManager());
            container.RegisterType<IAnalysisEngine, AnalysisEngine>(new ContainerControlledLifetimeManager());
            container.RegisterType<ConsoleApiPort>(new ContainerControlledLifetimeManager());
            container.RegisterType<ICollection<IReportWriter>>(new ContainerControlledLifetimeManager(), new InjectionFactory(WriterCollection));
            container.RegisterType<IApiPortOptions>(new ContainerControlledLifetimeManager(), new InjectionFactory(GetOptions));
            container.RegisterType<DocIdSearchRepl>(new ContainerControlledLifetimeManager());
            container.RegisterType<ISearcher<string>, ApiPortServiceSearcher>(new ContainerControlledLifetimeManager());

            // Register the default output format name
            container.RegisterInstance(DefaultOutputFormatInstanceName, "Excel");

            if (Console.IsOutputRedirected)
            {
                container.RegisterInstance<IProgressReporter>(new TextWriterProgressReporter(Console.Out));
            }
            else
            {
                container.RegisterType<IProgressReporter, ConsoleProgressReporter>(new ContainerControlledLifetimeManager());
            }

#if FEATURE_DESKTOP_CONFIGURATION // Unity configuration is only available in its desktop package
            // Load any customizations via Unity
            var fileMap = new ExeConfigurationFileMap
            {
                ExeConfigFilename = Path.Combine(GetApplicationDirectory(), "unity.config")
            };

            var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            var unitySection = (UnityConfigurationSection)configuration.GetSection("unity");

            return unitySection == null ? container : container.LoadConfiguration(unitySection);
#else // FEATURE_DESKTOP_CONFIGURATION
            // TODO : Allow runtime configuration through some non-.config means?
            return container;
#endif // FEATURE_DESKTOP_CONFIGURATION
        }
        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            container.RegisterType<IMovieDataAccess, YoutubeService>("YoutubeService");
            container.RegisterType<IMovieDataAccess, OMDBService>("OMDBService");
            container.RegisterInstance<IAppCache>(MovieTrailers.DataAccess.AppCache.Instance);
            container.RegisterInstance<IMovieTrailerService>(new MovieTrailerService(container.ResolveAll<IMovieDataAccess>()));
            return container;
        }
Beispiel #29
0
 internal static UnityContainer CreateUnityContainer()
 {
     var container = new UnityContainer();
     RegisterPages(container);
     RegisterViewModels(container);
     container.RegisterType<IWebcam, CustomWebcam>();
     container.RegisterInstance<IDataRepository>(new SerializerRepository(ConfigData.DataFile));
     container.RegisterInstance<ISessionData>(container.Resolve<SessionData>());
     return container;
 }
        public void ModuleManagerRunCalled()
        {
            // Have to use a non-mocked container because of IsRegistered<> extension method, Registrations property,and ContainerRegistration
            var container = new UnityContainer();

            var mockedModuleInitializer = new Mock<IModuleInitializer>();
            var mockedModuleManager = new Mock<IModuleManager>();
            var regionAdapterMappings = new RegionAdapterMappings();
            var serviceLocatorAdapter = new UnityServiceLocatorAdapter(container);
            var regionBehaviorFactory = new RegionBehaviorFactory(serviceLocatorAdapter);

            container.RegisterInstance<IServiceLocator>(serviceLocatorAdapter);
            container.RegisterInstance<UnityBootstrapperExtension>(new UnityBootstrapperExtension());
            container.RegisterInstance<IModuleCatalog>(new ModuleCatalog());
            container.RegisterInstance<IModuleInitializer>(mockedModuleInitializer.Object);
            container.RegisterInstance<IModuleManager>(mockedModuleManager.Object);
            container.RegisterInstance<RegionAdapterMappings>(regionAdapterMappings);

            container.RegisterInstance<SelectorRegionAdapter>(new SelectorRegionAdapter(regionBehaviorFactory));
            container.RegisterInstance<ItemsControlRegionAdapter>(new ItemsControlRegionAdapter(regionBehaviorFactory));
            container.RegisterInstance<ContentControlRegionAdapter>(new ContentControlRegionAdapter(regionBehaviorFactory));

            var bootstrapper = new MockedContainerBootstrapper(container);

            bootstrapper.Run();

            mockedModuleManager.Verify(mm => mm.Run(), Times.Once());
        }
 private void Application_Startup(object sender, StartupEventArgs e)
 {
     ioc.RegisterInstance(typeof(ILogging.ILoggingFactory), typeof(ILogging.ILoggingFactory).Name, logFactory, new Unity.ContainerControlledLifetimeManager());
     ioc.RegisterType(typeof(IRepo.IRepositoryFactory), typeof(Repo.RepositoryFactory), typeof(IRepo.IBankRepo).Name, new Unity.TransientLifetimeManager(), new Unity.InjectionMember[0]);
     ioc.RegisterType(typeof(IRepo.IBankRepo), typeof(Repo.BankRepo), typeof(IRepo.IBankRepo).Name, new Unity.TransientLifetimeManager(), new Unity.InjectionMember[0]);
     ioc.RegisterType(typeof(IRepo.IBelegRepo), typeof(Repo.BelegRepo), typeof(IRepo.IBankRepo).Name, new Unity.TransientLifetimeManager(), new Unity.InjectionMember[0]);
     ioc.RegisterType(typeof(IRepo.IFAKategorieRepo), typeof(Repo.FAKategorieRepo), typeof(IRepo.IBankRepo).Name, new Unity.TransientLifetimeManager(), new Unity.InjectionMember[0]);
 }
Beispiel #32
0
        private static void RegisterTypes(string[] args)
        {
            Container.RegisterType <IApplication, Application>();
            Container.RegisterInstance <IApplicationArguments>(new CommandLineArguments(args));

            Container.RegisterType <IValidatorManager, ValidatorManager>();
            Container.RegisterType <IPrinter, ConsolePrinter>();
            Container.RegisterType <IDateFormatter, DateFormatter>();
            Container.RegisterType <IFormatter, DateRangeFromatter>();
            Container.RegisterType <IArgumentWrapper, ArgumentWrapper>();
            Container.RegisterType <IEnvironment, EnvironmentControl>();
        }
Beispiel #33
0
        public static void Initialize()
        {
            var container = new Microsoft.Practices.Unity.UnityContainer();

            GlobalConfiguration.Configuration.DependencyResolver = new QMailer.UnityDependencyResolver(container);

            GlobalConfiguration.Configuration.FullUrl     = "http://localhost";
            GlobalConfiguration.Configuration.SenderEmail = "*****@*****.**";
            GlobalConfiguration.Configuration.SenderName  = "TestEmail";

            var existingBus = container.Resolve <Ariane.IServiceBus>();

            container.RegisterType <Ariane.IServiceBus, Ariane.SyncBusManager>(new ContainerControlledLifetimeManager(), new InjectionConstructor(existingBus));

            var bus = container.Resolve <Ariane.IServiceBus>();

            bus.Register.AddQueue(new QueueSetting()
            {
                AutoStartReading = true,
                Name             = GlobalConfiguration.Configuration.EmailBodyRequestedQueueName,
                TypeMedium       = typeof(Ariane.InMemoryMedium),
                TypeReader       = typeof(QMailer.Web.EmailBodyRequestedMessageReader)
            });
            bus.Register.AddQueue(new QueueSetting()
            {
                AutoStartReading = true,
                Name             = GlobalConfiguration.Configuration.SendEmailQueueName,
                TypeMedium       = typeof(Ariane.InMemoryMedium),
                TypeReader       = typeof(QMailer.SendEmailMessageReader)
            });

            QMailerService.ReplaceBusService(bus);
            QMailer.Web.QMailerConfig.Configure(container);

            var viewEngines = new Moq.Mock <ViewEngineCollection>();
            var fakeView    = new FakeView();

            viewEngines.Setup(i => i.FindView(Moq.It.IsAny <ControllerContext>(), "test", null))
            .Returns(new ViewEngineResult(fakeView, Moq.Mock.Of <IViewEngine>()));

            var fakeRenderer = new QMailer.Web.EmailViewRenderer(viewEngines.Object, "http://localhost", "~/emailviews");

            container.RegisterInstance <QMailer.Web.IEmailViewRenderer>(fakeRenderer, new ContainerControlledLifetimeManager());

            container.RegisterType <QMailer.ILogger, QMailer.DiagnosticsLogger>(new ContainerControlledLifetimeManager());
        }