Example #1
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Allow Any Certificates
            // This should not be the same in Production
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

            // Create the container as usual.
            var container = new Container();
            container.Options.PropertySelectionBehavior = new ImportPropertySelectionBehavior();
            container.Register<IErrorSignaler, ErrorSignaler>(Lifestyle.Singleton);
            container.Register<IHttpClientHelper, HttpClientHelper>(Lifestyle.Singleton);
            container.Register<IConfigurationHelper, ConfigurationHelper>(Lifestyle.Singleton);

            // SI Attributes Dependency Injection
            container.RegisterInitializer<BlogApiAuthorizationAttribute>(a => a.ErrorSignaler = container.GetInstance<ErrorSignaler>());
            container.RegisterInitializer<BlogAuthorizationAttribute>(a => a.ErrorSignaler = container.GetInstance<ErrorSignaler>());

            // This is an extension method from the integration package.
            container.RegisterMvcControllers(System.Reflection.Assembly.GetExecutingAssembly());
            container.RegisterMvcIntegratedFilterProvider();
            container.Verify();

            DependencyResolver.SetResolver(new SimpleInjector.Integration.Web.Mvc.SimpleInjectorDependencyResolver(container));
        }
Example #2
0
        private static Container ConfigureContainer()
        {
            var container = new Container();

              // Reset this line to reconfigure for production
              container.RegisterSingleton<ISettingsService>(new TestSettingsService());
              //container.RegisterSingleton<ISettingsService>(new ProductionSettingsService());

              container.Register<ILogger, NlogLoggerAdapter>();
              container.RegisterSingleton<IPlantPhotoService, PlantPhotoService>();
              container.RegisterSingleton<IImageRenameService, ImageRenameService>();
              container.RegisterSingleton<IRenameOperationsManager, RenameOperationsManager>();

              container.RegisterInitializer<IImageRenameService>(svc =>
              {
            svc.Logger = new NlogLoggerAdapter(LogManager.GetLogger("logFile"));
              });

              container.RegisterInitializer<IRenameOperationsManager>(mgr =>
              {
            mgr.ConsoleLogger = new NlogLoggerAdapter(LogManager.GetLogger("logConsole"));
              });

              return container;
        }
        private static void InitializeContainer(Container container)
        {
            var repositoryAssembly = typeof (MvcApplication).Assembly;

            var registrations =
                from type in repositoryAssembly.GetExportedTypes()
                where type.Namespace.Contains("MvcIoC.Models")
                where type.GetInterfaces().Any()
                select new
                           {
                               Service = type.GetInterfaces().First(),
                               Implementation = type
                           };

            foreach (var reg in registrations)
            {
                container.Register(reg.Service, reg.Implementation, Lifestyle.Transient);
            }

            container.RegisterInitializer<ProteinTrackerBasePage>(
                p => p.AnalyticsService = container.GetInstance<IAnalyticsService>());

            // For instance:
            // container.Register<IUserRepository, SqlUserRepository>();
        }
        public void ResgisterProperties <IService>(Action <IService> acction) where IService : class
        {
            _container.Options.AllowOverridingRegistrations = true;

            _container.Register <IService>();
            _container.RegisterInitializer <IService>(acction);

            _container.Options.AllowOverridingRegistrations = false;
        }
Example #5
0
        public void RegisterInitializer_BaseClass_RunsInitializerOnSubClass()
        {
            var container = new Container();
            container.Register<ITestService, TestService>();
            container.RegisterInitializer<TestContainer>(c => c.TestService = container.GetInstance<ITestService>());

            var testContainer = container.GetInstance<TestContainerDerivative>();

            testContainer.ShouldNotBeNull();
            testContainer.TestService.ShouldNotBeNull();
        }
Example #6
0
        static void Main(string[] args)
        {
            // Create a new container
            var container = new SimpleInjector.Container();

            // Configure the container (Register)
            container.Register <LogConfiguration>();
            container.Register <IAccount, AccountController>();

            container.Collection.Register <ILogger>(typeof(ConsoleLogger), typeof(CompositeLogger));
            container.Collection.Append <ILogger, FileLoger>();

            var assemblies = new[] { typeof(ICommand <>).Assembly };

            //container.Register(typeof(ICommand<>), assemblies);
            container.Collection.Register(assemblies);

            container.Register <IHandler <AHandler>, AHandler>();
            container.Register <IHandler <BHandler>, BHandler>();
            container.RegisterInitializer <IHandler>(hdl => hdl.ExecuteAsynchronously = true);

            container.Register <Transient>(Lifestyle.Transient);
            //container.Register<Scoped>(Lifestyle.Scoped);
            container.Register <Singleton1>(Lifestyle.Singleton);
            container.RegisterInstance(new Singleton2());
            container.RegisterSingleton <Singleton3>();

            // Solve: Cycling dependency
            container.RegisterInstance <IServiceProvider>(container);
            container.Register <ServiceFactory>();
            container.Register <AService>();
            container.Register <BService>();

            // Verify the container (optional)
            container.Verify();
            Console.WriteLine("Verified ====>");

            // Retrieve instances from the container (Resolve)
            DemoRegisterInitializer(container);

            DemoChangeValue <Transient>(container);
            //DemoChangeValue<Scoped>(container);
            DemoChangeValue <Singleton1>(container);
            DemoChangeValue <Singleton2>(container);
            DemoChangeValue <Singleton3>(container);

            var depenOnB = container.GetInstance <AService>();
            var depenOnA = container.GetInstance <BService>();
        }
        private static Container Bootstrap()
        {
            var container = new Container();

            // register database types
            container.Register<IDatabaseInitializer<UCosmicContext>, BrownfieldInitializer>();
            container.Register<ISeedData, BrownfieldSeeder>();
            container.Register<UCosmicContext>();
            container.Register<IWrapDataConcerns, DataConcernsWrapper>();
            container.RegisterInitializer<UCosmicContext>(container.InjectProperties);

            // register browsers
            container.RegisterSingle(() => new ChromeDriver(GetChromeDriverDirectory()));
            container.RegisterSingle(() => new InternetExplorerDriver());
            container.RegisterSingle(() => new FirefoxDriver());
            var browsers = AllBrowsers(container);
            container.RegisterAll(browsers);

            // register other stuff
            container.Register<IManageConfigurations, DotNetConfigurationManager>();

            container.Verify();
            return container;
        }
Example #8
0
        private static void Configure(ConsoleApp app)
        {
            _container = new Container();
            _container.Options.AllowOverridingRegistrations = true;

            app.Arguments = app.Arguments ?? new ArgumentTypeCollection();
            app.ViewEngines = app.ViewEngines ?? new ViewEngineCollection(_container);

            _container.RegisterInitializer<Command>(command =>
            {
                command.ViewEngines = app.ViewEngines;
            });

            CommandBuilder.Current.SetCommandFactory(new SimpleInjectorCommandFactory(_container));

            app.ViewEngines.Add(new MustacheViewEngine());

            app.Configure(_container);
            _container.Verify();
        }
Example #9
0
        public void RegisterServices()
        {
            _container.RegisterSingleton <IContainer>(() => this);

            _container.RegisterSingleton(() => Log.Instance);
            _container.RegisterSingleton <ControllerSettings>();

            _container.RegisterSingleton <IHealthService, HealthService>();
            _container.RegisterSingleton <DiscoveryServerService>();
            _container.RegisterSingleton <HttpServer>();

            _container.RegisterSingleton <IStorageService, StorageService>();
            _container.RegisterSingleton <ITimerService, TimerService>();
            _container.RegisterSingleton <ISystemEventsService, SystemEventsService>();
            _container.RegisterSingleton <ISystemInformationService, SystemInformationService>();
            _container.RegisterSingleton <IBackupService, BackupService>();

            _container.RegisterSingleton <IResourceService, ResourceService>();
            _container.RegisterInitializer <ResourceService>(s => s.Initialize());

            _container.RegisterSingleton <IApiService, ApiService>();
            _container.RegisterSingleton <AzureCloudApiDispatcherEndpointService>();
            _container.RegisterSingleton <LocalHttpServerApiDispatcherEndpointService>();

            _container.RegisterSingleton <IDateTimeService, DateTimeService>();
            _container.RegisterSingleton <ISchedulerService, SchedulerService>();

            _container.RegisterSingleton <INotificationService, NotificationService>();
            _container.RegisterInitializer <NotificationService>(s => s.Initialize());

            _container.RegisterSingleton <ISettingsService, SettingsService>();
            _container.RegisterInitializer <SettingsService>(s => s.Initialize());

            _container.RegisterSingleton <II2CBusService, BuiltInI2CBusService>();
            _container.RegisterSingleton <IPi2GpioService, Pi2GpioService>();
            _container.RegisterSingleton <CCToolsBoardService>();
            _container.RegisterSingleton <RemoteSocketService>();

            _container.RegisterSingleton <IDeviceService, DeviceService>();

            _container.RegisterSingleton <IComponentService, ComponentService>();
            _container.RegisterSingleton <ActuatorFactory>();
            _container.RegisterSingleton <SensorFactory>();

            _container.RegisterSingleton <IAreaService, AreaService>();

            _container.RegisterSingleton <IAutomationService, AutomationService>();
            _container.RegisterSingleton <AutomationFactory>();

            _container.RegisterSingleton <IPersonalAgentService, PersonalAgentService>();
            _container.RegisterSingleton <SynonymService>();

            _container.RegisterSingleton <IOutdoorTemperatureService, OutdoorTemperatureService>();
            _container.RegisterSingleton <IOutdoorHumidityService, OutdoorHumidityService>();
            _container.RegisterSingleton <IDaylightService, DaylightService>();
            _container.RegisterSingleton <IWeatherService, WeatherService>();
            _container.RegisterSingleton <OpenWeatherMapService>();
            _container.RegisterSingleton <ControllerSlaveService>();

            _container.RegisterSingleton <ITwitterClientService, TwitterClientService>();
            _container.RegisterSingleton <ITelegramBotService, TelegramBotService>();
        }
Example #10
0
        public void RegisterServices()
        {
            _container.RegisterSingleton <IContainer>(() => this);

            _container.RegisterSingleton <ControllerSettings>();

            _container.RegisterSingleton <ILogService, LogService>();
            _container.RegisterSingleton <IHealthService, HealthService>();
            _container.RegisterSingleton <IDateTimeService, DateTimeService>();
            _container.RegisterSingleton <ISchedulerService, SchedulerService>();
            _container.RegisterSingleton <DiscoveryServerService>();

            _container.RegisterSingleton <IStorageService, StorageService>();
            _container.RegisterSingleton <ITimerService, TimerService>();
            _container.RegisterSingleton <ISystemEventsService, SystemEventsService>();
            _container.RegisterSingleton <ISystemInformationService, SystemInformationService>();
            _container.RegisterSingleton <IBackupService, BackupService>();

            _container.RegisterSingleton <IResourceService, ResourceService>();
            _container.RegisterInitializer <ResourceService>(s => s.Initialize());

            _container.RegisterSingleton <IApiDispatcherService, ApiDispatcherService>();
            _container.RegisterSingleton <HttpServer>();
            _container.RegisterSingleton <HttpServerService>();
            _container.RegisterSingleton <AzureCloudService>();
            _container.RegisterSingleton <CloudConnectorService>();

            _container.RegisterSingleton <INotificationService, NotificationService>();
            _container.RegisterInitializer <NotificationService>(s => s.Initialize());

            _container.RegisterSingleton <ISettingsService, SettingsService>();
            _container.RegisterInitializer <SettingsService>(s => s.Initialize());

            _container.RegisterSingleton <II2CBusService, BuiltInI2CBusService>();
            _container.RegisterSingleton <IGpioService, GpioService>();
            _container.RegisterSingleton <IDeviceMessageBrokerService, DeviceMessageBrokerService>();
            _container.RegisterInitializer <DeviceMessageBrokerService>(s => s.Initialize());
            _container.RegisterSingleton <InterruptMonitorService>(); // TODO: Add interface for testing etc.

            _container.RegisterSingleton <CCToolsDeviceService>();
            _container.RegisterSingleton <RemoteSocketService>();
            _container.RegisterSingleton <SonoffDeviceService>();
            _container.RegisterSingleton <OutpostDeviceService>();

            _container.RegisterSingleton <IDeviceRegistryService, DeviceRegistryService>();
            _container.RegisterSingleton <IAreaRegistryService, AreaRegistryService>();
            _container.RegisterSingleton <IComponentRegistryService, ComponentRegistryService>();
            _container.RegisterSingleton <IAutomationRegistryService, AutomationRegistryService>();

            _container.RegisterSingleton <ActuatorFactory>();
            _container.RegisterSingleton <SensorFactory>();
            _container.RegisterSingleton <AutomationFactory>();

            _container.RegisterSingleton <IPersonalAgentService, PersonalAgentService>();

            _container.RegisterSingleton <IOutdoorTemperatureService, OutdoorTemperatureService>();
            _container.RegisterSingleton <IOutdoorHumidityService, OutdoorHumidityService>();
            _container.RegisterSingleton <IDaylightService, DaylightService>();
            _container.RegisterSingleton <IWeatherService, WeatherService>();
            _container.RegisterSingleton <OpenWeatherMapService>();
            _container.RegisterSingleton <ControllerSlaveService>();

            _container.RegisterSingleton <ITwitterClientService, TwitterClientService>();
            _container.RegisterSingleton <ITelegramBotService, TelegramBotService>();

            _container.RegisterSingleton <IStatusService, StatusService>();
        }
Example #11
0
        public void RegisterServices()
        {
            _container.RegisterSingleton <IContainer>(() => this);

            foreach (var customService in _options.CustomServices)
            {
                _container.RegisterSingleton(customService);
            }

            _container.RegisterCollection <ILogAdapter>(_options.LogAdapters);
            _container.RegisterSingleton <ILogService, LogService>();
            _container.RegisterSingleton <IHealthService, HealthService>();
            _container.RegisterSingleton <IDateTimeService, DateTimeService>();
            _container.RegisterSingleton <ISchedulerService, SchedulerService>();
            _container.RegisterSingleton <DiscoveryServerService>();

            _container.RegisterSingleton <IConfigurationService, ConfigurationService>();
            _container.RegisterInitializer <ConfigurationService>(s => s.Initialize());

            _container.RegisterSingleton <IStorageService, StorageService>();
            _container.RegisterSingleton <ITimerService, TimerService>();
            _container.RegisterSingleton <ISystemEventsService, SystemEventsService>();
            _container.RegisterSingleton <ISystemInformationService, SystemInformationService>();
            _container.RegisterSingleton <IBackupService, BackupService>();

            _container.RegisterSingleton <IResourceService, ResourceService>();
            _container.RegisterInitializer <ResourceService>(s => s.Initialize());

            _container.RegisterSingleton <IApiDispatcherService, ApiDispatcherService>();
            _container.RegisterSingleton <HttpServerService>();
            _container.RegisterSingleton <AzureCloudService>();
            _container.RegisterSingleton <CloudConnectorService>();

            _container.RegisterSingleton <INotificationService, NotificationService>();
            _container.RegisterInitializer <NotificationService>(s => s.Initialize());

            _container.RegisterSingleton <ISettingsService, SettingsService>();
            _container.RegisterInitializer <SettingsService>(s => s.Initialize());

            _container.RegisterSingleton <II2CBusService, I2CBusService>();
            _container.RegisterSingleton <IGpioService, GpioService>();
            _container.RegisterSingleton <IMessageBrokerService, MessageBrokerService>();
            _container.RegisterSingleton <IInterruptMonitorService, InterruptMonitorService>();

            _container.RegisterSingleton <IDeviceMessageBrokerService, DeviceMessageBrokerService>();
            _container.RegisterInitializer <DeviceMessageBrokerService>(s => s.Initialize());

            _container.RegisterSingleton <IRemoteSocketService, RemoteSocketService>();

            _container.RegisterSingleton <CCToolsDeviceService>();
            _container.RegisterSingleton <SonoffDeviceService>();

            _container.RegisterSingleton <IDeviceRegistryService, DeviceRegistryService>();
            _container.RegisterSingleton <IAreaRegistryService, AreaRegistryService>();
            _container.RegisterSingleton <IComponentRegistryService, ComponentRegistryService>();
            _container.RegisterSingleton <IAutomationRegistryService, AutomationRegistryService>();
            _container.RegisterSingleton <IScriptingService, ScriptingService>();

            _container.RegisterSingleton <ActuatorFactory>();
            _container.RegisterSingleton <SensorFactory>();
            _container.RegisterSingleton <AutomationFactory>();

            _container.RegisterSingleton <IPersonalAgentService, PersonalAgentService>();

            _container.RegisterSingleton <IOutdoorService, OutdoorService>();
            _container.RegisterSingleton <IDaylightService, DaylightService>();
            _container.RegisterSingleton <OpenWeatherMapService>();
            _container.RegisterSingleton <ControllerSlaveService>();

            _container.RegisterSingleton <ITwitterClientService, TwitterClientService>();
            _container.RegisterSingleton <ITelegramBotService, TelegramBotService>();

            _container.RegisterSingleton <IStatusService, StatusService>();
        }
        public Container GetInitializedContainer(IAppBuilder app)
        {
            var container = new Container();

            container.RegisterSingle(app);


            //allows objects to be reused when inside web request, or created fresh when used on background threads or outside a request context
            var hybridLifestyle = Lifestyle.CreateHybrid(
                () => HttpContext.Current != null, new WebRequestLifestyle(), Lifestyle.Transient);

            container.RegisterPerWebRequest<TicketDeskContextSecurityProvider>();

            container.Register(() => new TdPushNotificationContext(), hybridLifestyle);

            container.Register(() => HttpContext.Current != null ?
                    new TdDomainContext(container.GetInstance<TicketDeskContextSecurityProvider>()) :
                    new TdDomainContext(),
                hybridLifestyle);

            container.Register(() => new TdIdentityContext(), hybridLifestyle);

            container.Register<IUserStore<TicketDeskUser>>(() =>
                new UserStore<TicketDeskUser>(container.GetInstance<TdIdentityContext>()), 
                hybridLifestyle);

            container.Register<IRoleStore<TicketDeskRole, string>>(() =>
                new RoleStore<TicketDeskRole>(container.GetInstance<TdIdentityContext>()), 
                hybridLifestyle);


            container.RegisterPerWebRequest(() =>
            {
                IOwinContext context;
                try
                {
                    context = HttpContext.Current.GetOwinContext();
                }
                catch (InvalidOperationException)
                {
                    //avoid exception when this is called before the owin environment is fully initialized
                    if (container.IsVerifying())
                    {
                        return new FakeAuthenticationManager();
                    }
                    throw;
                }

                return context.Authentication;
            }
                );

            container.RegisterPerWebRequest<SignInManager<TicketDeskUser, string>, TicketDeskSignInManager>();

            container.RegisterPerWebRequest<TicketDeskRoleManager>();

            container.RegisterInitializer<TicketDeskUserManager>(manager =>
                manager.ConfigureDataProtection(app));


            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

            return container;
        }
        internal static Container Bootstrap(ContainerConfiguration configuration)
        {
            var container = new Container();

            /**
             * Entity Framework Dependency Injection:
             *
             * There are 2 main dependencies: database initialization, and database seeding.
             * Whenever the domain entity model changes, the SQL db will be out of sync.
             * The DropOnModelChangeInitializer only drops and recreates the database when the entity model changes.
             * The DropAlwaysInitializer drops and recreates the database after each new solution rebuild.
             * The BrownfieldInitializer never drops the database, even if the entity model does not match.
             * However the initializer only drops and recreates the database, all tables will be empty.
             * To populate with new data, use the CompositeDbSeeder.
             * It uses a combination of DbContext and raw SQL to populate the database.
             * When the BrownfieldDbSeeder is injected, no data will be seeded.
             *
             * 2012.02.22: There is now a DevelopmentDataSqlSeeder, which is much faster than the CompositeDbSeeder.
             *
             * When checking in this file, the DropOnModelChangeInitializer and DevelopmentDataSqlSeeder
             * should be active. All other seeders and initializers should be commented out.
             */
            if (configuration.IsDeployedToCloud)
            {
                container.Register<IDatabaseInitializer<UCosmicContext>, BrownfieldInitializer>();
                //container.Register<ISeedData, BrownfieldSeeder>();
            }
            else
            {
                container.Register<IDatabaseInitializer<UCosmicContext>, DropOnModelChangeInitializer>();
                //container.Register<IDatabaseInitializer<UCosmicContext>, DropAlwaysInitializer>();
                //container.Register<IDatabaseInitializer<UCosmicContext>, BrownfieldInitializer>();

                container.Register<ISeedData, CompositeSqlSeeder>();
                //container.Register<ISeedData, CompositeEntitySeeder>();
                //container.Register<ISeedData, BrownfieldSeeder>();
            }

            // register 1 DbContext for all implemented interfaces
            container.RegisterPerWebRequest<UCosmicContext>();
            container.Register<IUnitOfWork>(container.GetInstance<UCosmicContext>);
            container.Register<IQueryEntities>(container.GetInstance<UCosmicContext>);
            container.Register<ICommandEntities>(container.GetInstance<UCosmicContext>);
            container.RegisterInitializer<UCosmicContext>(container.InjectProperties);

            // other interfaces related to DbContext
            //container.Register<ICommandObjects, ObjectCommander>();

            // general purpose interfaces
            container.Register<IStorePasswords, DotNetMembershipProvider>();
            container.Register<ISignUsers, DotNetFormsAuthentication>();
            container.Register<IManageConfigurations, DotNetConfigurationManager>();
            container.Register<ILogExceptions, ElmahExceptionLogger>();
            container.Register<IConsumeHttp, WebRequestHttpConsumer>();
            container.Register<ISendMail, SmtpMailSender>();

            // SAML interfaces
            container.Register<IProvideSaml2Service, ComponentSpaceSaml2ServiceProvider>();
            container.Register<IParseSaml2Metadata, ComponentSpaceSaml2MetadataParser>();
            container.Register<IStoreSamlCertificates, RealSamlCertificateStorage>();

            // NGeo interfaces
            container.RegisterPerWebRequest<IConsumeGeoNames, GeoNamesClient>();
            container.RegisterPerWebRequest<IContainGeoNames>(() => new GeoNamesContainer(configuration.GeoNamesUserName));
            container.RegisterPerWebRequest<IConsumeGeoPlanet, GeoPlanetClient>();
            container.RegisterPerWebRequest<IContainGeoPlanet>(() => new GeoPlanetContainer(configuration.GeoPlanetAppId));
            container.RegisterPerWebRequest<IConsumePlaceFinder, PlaceFinderClient>();

            // load assemblies for IoC reflection
            var assemblies = AppDomain.CurrentDomain.GetAssemblies()
                .Where(a => !a.FullName.StartsWith("Microsoft.Web.Mvc,"))
                .ToArray();

            // fluent validation open generics
            container.RegisterManyForOpenGeneric(typeof(IValidator<>), assemblies);

            // add unregistered type resolution for objects missing an IValidator<T>
            container.RegisterSingleOpenGeneric(typeof(IValidator<>), typeof(UnspecifiedValidator<>));

            // open generic decorator chains http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91
            container.RegisterManyForOpenGeneric(typeof(IHandleCommands<>), assemblies);

            // send emails in a new thread
            container.RegisterRunAsyncCommandHandlerProxy<SendEmailMessageCommand>();

            // register fluent validators on commands
            container.RegisterDecorator(typeof(IHandleCommands<>),
                typeof(FluentValidationCommandDecorator<>));
            //container.RegisterOpenGenericDecorator(typeof(IHandleCommands<>),
            //    typeof(FluentValidationCommandDecorator<>));

            // query processing
            container.RegisterSingle<SimpleQueryProcessor>();
            container.Register<IProcessQueries>(container.GetInstance<SimpleQueryProcessor>);
            container.RegisterManyForOpenGeneric(typeof(IHandleQueries<,>), assemblies);

            // verify container
            container.Verify();

            return container;
        }