Esempio n. 1
0
        public void Register(Container container)
        {
            container.RegisterSingleton(() =>
            {
                LicenseUtils.RegisterLicense("2283-e1JlZjoyMjgzLE5hbWU6TWVkWENoYW5nZSxUeXBlOkluZGllLEhhc2g6TU" +
                "FyaTVzNGdQcEdlc0pqd1ZIUXVlL0lacDBZcCt3TkFLY0UyMTlJblBuMzRLNWFRb" +
                "HBYN204aGkrQXlRYzUvZnNVUlZzWXd4NjR0OFlXZEpjNUNYRTdnMjBLR0ZjQmhG" +
                "dTFNMHZVazJqcHdQb1RrbStDaHNPRm11Qm50TnZzOTkwcHAzRkxtTC9idThMekN" +
                "lTVRndFBORzBuREZ0WGJUdzdRMi80K09lQ2tZPSxFeHBpcnk6MjAxNi0wMi0xOX" +
                "0=");

                var rabbitMqHost = ConfigurationManager.AppSettings["RabbitMQHost"];
                if (string.IsNullOrEmpty(rabbitMqHost)) throw new Exception("You must provide a 'RabbitMQHost' app setting.");
                return new RabbitMqServer(rabbitMqHost)
                {
                    ErrorHandler = exception =>
                    {
                        Logger.For<RabbitMqServer>().Error("There was an error processing a message.", exception);
                    }
                };
            });
            container.RegisterSingleton<ICommandBus, CommandBus>();
            container.RegisterSingleton<IEventBus, EventBus>();
            container.RegisterSingleton<IBusLifetime, BusLifetime>();
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            var container = new Container();
            RegisterInfrastructure(container);
            var assemblies = GetAssemblies().ToArray();
            container.RegisterSingleton<IMediator, Mediator>();
            container.RegisterSingleton(new SingleInstanceFactory(container.GetInstance));
            container.RegisterSingleton(new MultiInstanceFactory(container.GetAllInstances));
            container.RegisterCollection(typeof(IAsyncNotificationHandler<>), assemblies);
            container.Verify();

            var mediator = container.GetInstance<IMediator>();
            var commandsDbContext = container.GetInstance<ICommandsDbContext>();

            Console.Write("creating users...");
            Task.WaitAll(CreateUsersAsync(commandsDbContext, mediator));
            Console.WriteLine("done!");

            Console.Write("creating areas...");
            Task.WaitAll(CreateAreasAsync(commandsDbContext, mediator));
            Console.WriteLine("done!");

            Console.Write("creating ideas...");
            Task.WaitAll(CreateIdeasAsync(commandsDbContext, mediator));
            Console.WriteLine("done!");

            Console.Write("creating idea comments...");
            Task.WaitAll(CreateIdeaCommentsAsync(commandsDbContext, mediator));
            Console.WriteLine("done!");

            Console.WriteLine("Feeding complete!");
            Console.ReadLine();
        }
		public static void InitializeFruit(Container container)
		{
			container.RegisterSingleton<IFruitsFactory, FruitsFactory>();
			container.RegisterSingleton<IFruitItemRepository, FruitItemRepository>();
			container.RegisterSingleton<IFruitListViewModelFactory, FruitListViewModelFactory>();
			container.RegisterSingleton<IFruitListItemViewModelFactory, FruitListItemViewModelFactory>();
		}
        public void RegisterServices(Container container)
        {
            container.RegisterSingleton<IConfiguration, EnvironmentAwareAppSettingsConfiguration>();
            container.RegisterSingleton(() =>
            {
                var config = container.GetInstance<IConfiguration>();
                var useRedis = config.Get("UseRedis");

                IDataServiceFactory factory;

                if (bool.Parse(useRedis))
                {
                    factory = new RedisDataServiceFactory(config);
                }
                else
                {
                    factory = new DirectDataServiceFactory();
                }

                return factory;
            });

            container.RegisterSingleton(() => container.GetInstance<IDataServiceFactory>().Create());
            container.RegisterSingleton<IAppSettings, AppSettings>();
        }
Esempio n. 5
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;
        }
 public void Configure(Container container)
 {
     container.RegisterSingleton<IUserRepository, UserRespository>();
     container.RegisterSingleton<IShoppingItemRepository, ShoppingItemRepository>();
     container.RegisterSingleton<IShoppingListRepository, ShoppingListRepository>();
     container.RegisterSingleton<IFriendRepository, FriendRepository>();
 }
Esempio n. 7
0
 public void Register(Container container)
 {
     container.RegisterSingleton<IMapper, Mapper>();
     container.RegisterSingleton<IConnectionStringProvider, ConnectionStringProvider>();
     container.RegisterSingleton<IDbConnectionProvider, SqlConnectionProvider>();
     container.RegisterSingleton<IEmailSender, EmailSender>();
     container.RegisterSingleton<IPathResolver, PathResolver>();
 }
Esempio n. 8
0
 private static Container ConfigureIoc()
 {
     var container = new Container();
     container.RegisterSingleton(() => new RemoteClientListenerFactory().Build());
     container.RegisterSingleton<CommandLineProcessor>();
     container.RegisterSingleton<ICommandLineHandlerLocator>(() => new CommandLineHandlerLocator(container));
     container.RegisterSingleton<Context>();
     container.RegisterSingleton<ClientList>();
     return container;
 }
Esempio n. 9
0
 private static void IocSetup(Container container)
 {
     var assemblies = GetAssemblies().ToArray();
     
     container.RegisterSingleton<IMediator, Mediator>();
     container.RegisterSingleton<ILog, Log>();
     container.Register(typeof(IQueryHandler<,>), assemblies);
     container.RegisterCollection(typeof(IQueryHandler<,>), assemblies);
     container.RegisterSingleton(typeof(DbContext), new DbEntities());
 }
Esempio n. 10
0
 public void Register(Container container)
 {
     container.RegisterSingleton<ICache, Cache>();
     container.RegisterSingleton<IRedisClientsManager>(() =>
     {
         var readWrite = System.Configuration.ConfigurationManager.AppSettings["RedisReadWrite"];
         var read = System.Configuration.ConfigurationManager.AppSettings["RedisRead"];
         return new PooledRedisClientManager(readWrite.Split(';'), read.Split(';'));
     });
 }
Esempio n. 11
0
        protected override void OnStart(string[] args)
        {
            _container = new Container();

            _container.RegisterSingleton<IAchievementPushService, AchievementPushService>();
            _container.RegisterSingleton<IAchievementService, AchievementService>();
            _container.RegisterSingleton<IActivityGroupingService, ActivityGroupingService>();
            _container.RegisterSingleton<IDatabaseService, DatabaseService>();
            _container.RegisterSingleton<IFitocracyService, FitocracyService>();
            _container.RegisterSingleton<IScrapingService, ScrapingService>();
            _container.RegisterSingleton<IUserPullService, UserPullService>();
            _container.RegisterSingleton<IWebRequestService, WebRequestService>();
            _container.RegisterSingleton<IWorkoutPullService, WorkoutPullService>();

            _container.RegisterCollection<IAchievementProvider>(
                GetType().Assembly.GetTypes()
                         .Where(typeof (IAchievementProvider).IsAssignableFrom)
                         .Where(type => type.IsClass));

            _container.RegisterDecorator<IWebRequestService, ThrottledWebRequestDecorator>(Lifestyle.Singleton);

            _container.Verify();

            _cancelSource = new CancellationTokenSource();
            _task = Task.Factory.StartNew(Run, _cancelSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }
        public static void RegisterDependencies()
        {
            var container = new Container {Options = {DefaultScopedLifestyle = new WebRequestLifestyle()}};

            // Container
            container.Register<IServiceProvider>(() => container);

            // Request (command/query) dispatcher
            container.Register<IRequestDispatcher, RequestDispatcher>();

            // Command handlers
            container.Register(typeof (ICommandHandler<>), new[] {typeof (TabService).Assembly});
            container.RegisterDecorator(typeof (ICommandHandler<>), typeof (ValidationDecoratorCommandHandler<>));
            container.RegisterDecorator(typeof (ICommandHandler<>), typeof (LoggingDecoratorCommandHandler<>));

            // Query handlers
            container.Register(typeof (IQueryHandler<,>), new[] {typeof (TabReadModel).Assembly});

            // Validators
            container.RegisterSingleton(typeof (IValidator<>), typeof (CompositeValidator<>));
            container.AppendToCollection(typeof (IValidator<>), typeof (DataAnnotationsValidator<>));
            container.RegisterCollection(typeof (IValidator<>), typeof (MvcApplication).Assembly);

            // Data annotations validators
            container.Register(typeof (IValidationAttributeValidator<>), new[] {typeof (IValidationAttributeValidator<>).Assembly});

            // Loggers
            container.RegisterSingleton<ILoggerFactory, NLogLoggerFactory>();

            // Action filters
            container.RegisterCollection(typeof (IActionFilter<>), typeof (MvcApplication).Assembly);

            // Repository
            container.Register<IEventStore, InMemoryEventStore>();

            // Aggregate factory
            container.Register<IAggregateFactory, AggregateFactory>();

            // Event publisher
            container.Register<IEventPublisher>(() => new EventPublisher(type => container.GetAllInstances(type), container.GetInstance<ILoggerFactory>()));

            // Event handlers
            container.RegisterCollection(typeof (IEventSubscriber<>), new[] {typeof (TabReadModel).Assembly});

            // View model database
            container.RegisterSingleton<IReadModelDatabase, InMemoryReadModelDatabase>();

            // Verify
            container.Verify();

            System.Web.Mvc.DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
            System.Web.Mvc.GlobalFilters.Filters.Add(new ActionFilterDispatcher(type => container.GetAllInstances(type)));
            ServiceProvider = container;
        }
Esempio n. 13
0
        public DomainTestHarness()
        {
            _container = new Container();
             _container.RegisterSingleton<IApplicationSettings>(new Mock<IApplicationSettings>().Object);
             _container.RegisterSingleton<IAnalyticsRepository<Contact>>(() => new Mock<IAnalyticsRepository<Contact>>().Object);
             _container.RegisterSingleton<IAnalyticsRepository<Interaction>>(() => new Mock<IAnalyticsRepository<Interaction>>().Object);
             _container.RegisterSingleton<IContactService, xDBContactService>();
             _container.RegisterSingleton<IInteractionService, xDBInteractionService>();

             _fixture = new Fixture();
        }
        /// <summary>
        /// Configure the runtime dependencies
        /// </summary>
        protected override void Configure()
        {
            //Check database:
            Db.ConfigureMigrations();

            container = new Container();

            container.RegisterSingleton<IWindowManager, WindowManager>();
            container.RegisterSingleton<IEventAggregator, EventAggregator>();
            container.Register<IShell, ShellViewModel>();
            container.RegisterSingleton<Func<Db>>(() => new Db());
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BootstrapBundleConfig.RegisterBundles();

            var container = new Container();

            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

            container.RegisterSingleton<ILinqToLdapLogger>(new SimpleTextLogger());

            container.RegisterSingleton<ILdapConfiguration>(() =>
            {
                var config = new LdapConfiguration()
                    .MaxPageSizeIs(50)
                    .LogTo(container.GetInstance<ILinqToLdapLogger>());

                //Note the optional parameters available on AddMapping.
                //We can perform "late" mapping on certain values, 
                //even for auto and attribute based mapping.
                config.AddMapping(new OrganizationalUnitMap())
                      .AddMapping(new AttributeClassMap<User>());

                // I explicitly mapped User, but I can also let it 
                // get mapped the first time we query for users.
                // This only applies to auto and attribute-based mapping.

                config.ConfigurePooledFactory("directory.utexas.edu")
                      .AuthenticateBy(AuthType.Anonymous)
                      .MinPoolSizeIs(0)
                      .MaxPoolSizeIs(5)
                      .UsePort(389)
                      .ProtocolVersion(3);

                return config;
            });

            //simple context per request only when requested
            container.Register<IDirectoryContext>(() => container.GetInstance<ILdapConfiguration>().CreateContext(), Lifestyle.Scoped);

            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
            

            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
            
            container.Verify();
        }
        public static void RegisterSingleInterfacesAndType <T>(this Container container, IEnumerable <Type> types)
        {
            var ifaceType = typeof(T);

            foreach (var s in types)
            {
                container.RegisterSingleton(s, s);
                foreach (var i in s.GetInterfaces().Where(x => Predicate(x, ifaceType)))
                {
                    container.RegisterSingleton(i, () => container.GetInstance(s));
                }
            }
        }
Esempio n. 17
0
        protected override IServiceProvider BootstrapInternal(ILoggerFactory loggerFactory) {
            var container = new Container();

            if (loggerFactory != null) {
                container.RegisterSingleton<ILoggerFactory>(loggerFactory);
                container.RegisterSingleton(typeof(ILogger<>), typeof(Logger<>));
            }

            container.RegisterSingleton<ICacheClient>(() => new InMemoryCacheClient());
            container.RegisterSingleton<ILockProvider>(() => new CacheLockProvider(container.GetInstance<ICacheClient>(), container.GetInstance<IMessageBus>(), loggerFactory));

            return container;
        }
Esempio n. 18
0
        public void RegisterServices(Container container, CompositionRootSettings settings)
        {
            if (settings.FluentValidationAssemblies == null) return;

            ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure;

            container.RegisterSingleton<IValidatorFactory, SimpleInjectorValidatorFactory>();
            container.RegisterSingleton<IProcessValidation, ValidationProcessor>();

            container.Register(typeof(IValidator<>), settings.FluentValidationAssemblies);

            // Add unregistered type resolution for objects missing an IValidator<T>
            container.RegisterConditional(typeof(IValidator<>), typeof(ValidateNothingDecorator<>), Lifestyle.Singleton, context => !context.Handled);
        }
Esempio n. 19
0
        public void Register(Container container)
        {
            container.RegisterSingleton(() =>
            {
                var rabbitMqServer = new RabbitMQServer();
                // TODO set hostname
                rabbitMqServer.Startup();
                return rabbitMqServer;
            });

            container.RegisterSingleton<ICommandBus, CommandBus>();
            container.RegisterSingleton<IEventBus, EventBus>();
            container.RegisterSingleton<IMessageChannel, MessageChannel>();
        }
Esempio n. 20
0
        public void Register(Container container)
        {
            container.RegisterSingleton<IUserStore<ApplicationUser, Guid>, ApplicationUserStore>();
            container.RegisterSingleton<IIdentityMessageService, ApplicationIdentityMessageService>();
            container.RegisterSingleton<ApplicationUserManager>();
            container.RegisterSingleton<IAvatarService, AvatarService>();

            container.RegisterPerWebRequest<ApplicationSignInManager>();
            container.RegisterPerWebRequest<IUserContext, UserContext>();
            container.RegisterPerWebRequest<IContextService, ContextService>();

            container.RegisterMvcIntegratedFilterProvider();

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
Esempio n. 21
0
        public static Container Bootstrap()
        {
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

            BusinessLayerBootstrapper.Bootstrap(container);

            container.RegisterSingleton<IPrincipal>(new HttpContextPrincipal());
            container.RegisterSingleton<ILogger>(new DebugLogger());

            container.Verify();

            return container;
        }
Esempio n. 22
0
        public void Configuration(IAppBuilder app)
        {
            var container = new Container();            
            container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
            container.RegisterSingleton<DbContext>(() => new MyDbContext("ApSec"));
            container.RegisterSingleton<AppUserStore>();
            container.RegisterSingleton<AppUserManager>();

            container.Verify();
            var config = ConfigureWebApi();
            config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);

            app.UseWebApi(config);

        }
Esempio n. 23
0
        private static Container Bootstrap()
        {
            var container = new Container();

            container.RegisterSingleton<Jira.REST.Jira>();

            container.RegisterSingleton<MainWindow>();
            container.RegisterSingleton<MainWindowViewModel>();

            container.RegisterSingleton<LoginViewModel>();
            container.RegisterSingleton<ProjectViewModel>();

            container.RegisterSingleton<ScreenViewModel>();

            container.RegisterCollection<IPresentationViewModel>(
                new[] {
                    typeof(LoginViewModel),
                    typeof(ProjectViewModel)
                }
            );

            container.RegisterSingleton<ILoginView, LoginView>();
            container.RegisterSingleton<IProjectView, ProjectView>();

            // Register your windows and view models:
            //container.RegisterSingle<MainWindow>();
            //container.RegisterSingle<MainWindowViewModel>();
            //container.RegisterSingle<StatusViewModel>();

            //container.RegisterSingle<TravelTabDbContext>(() => new TravelTabDbContext());

            //container.Register<ITimeZoneManager, TimeZoneManager>();
            //container.Register<ITimeZoneStrategy, GoogleTimeZoneStrategy>();

            //container.Register<ICoordinatesStrategy, GoogleCoordinatesStrategy>();
            //container.Register<ICoordinatesManager, CoordinatesManager>();

            //container.RegisterAll<ICommerceCategoriesStrategy>(typeof(ViatorCommerceCategoriesStrategy), typeof(TravelTabCommerceCategoriesStrategy));

            //container.Register<ICommerceCategoriesManager, CommerceCategoriesManager>();

            //container.RegisterSingle<ICommerceRankingStrategy, ViatorCommerceRankingStrategy>();
            //container.Register<ICommerceRankingManager, CommerceRankingManager>();

            //container.Register<IViatorService>(() => ViatorService.Factory());

            //var allUpdateTasks = AppDomain.CurrentDomain.GetAssemblies()
            //											.SelectMany(x => x.GetTypes())
            //											.Where(mytype => mytype.GetInterfaces()
            //																	.Contains(typeof(IUpdateTask)) &&
            //																	mytype.Name != "UpdateTask");

            //container.RegisterAll<IUpdateTask>(allUpdateTasks);

            container.Verify();

            return container;
        }
Esempio n. 24
0
        public void RegisterServices(Container container, CompositionRootSettings settings)
        {
            if (settings.ViewModelAssemblies == null) return;

            container.RegisterSingleton<IProcessViewModels, ViewModelProcessor>();

            container.Register(typeof(IHandleViewModel<>), settings.ViewModelAssemblies);
            container.Register(typeof(IHandleViewModel<,>), settings.ViewModelAssemblies);

            container.RegisterDecorator(
                typeof(IHandleViewModel<>),
                typeof(ViewModelLifetimeScopeDecorator<>),
                Lifestyle.Singleton
            );

            container.RegisterDecorator(
                typeof(IHandleViewModel<,>),
                typeof(ViewModelWithArgumentLifetimeScopeDecorator<,>),
                Lifestyle.Singleton
            );

            container.RegisterDecorator(
                 typeof(IHandleViewModel<,>),
                 typeof(ViewModelWithArgumentNotNullDecorator<,>),
                Lifestyle.Singleton
            );
        }
        public static Container Create(ApplicationBootstrapConfig config)
        {
            var container = new Container();
            container.Options.AllowOverridingRegistrations = true;
            container.Register<IServiceProvider>(() => container);

            container.RegisterMediator(config.Assemblies.ToArray());
            container.Register<ITaskRepository, EfTaskRepository>();
            container.Register<IUnitOfWork>(() => new UnitOfWork(new MyAppContext().AsCommandContext()), config.UnitOfWorkLifestyle);
            container.Register<IQueryContext>(() => new QueryContext(new MyAppContext().AsQueryContext()), config.UnitOfWorkLifestyle);
            container.RegisterSingleton<IConnectionProvider, ConnectionProvider>();
            container.RegisterCollection(typeof(IValidator<>), config.Assemblies);

            var commandDecorators = new List<Type>
            {
                typeof(UnitOfWorkHandler<,>),
                typeof(TransactionHandler<,>),
                typeof(ValidatorHandler<,>),
                typeof(LogHandler<,>)
            };

            container.RegisterRequestHandlerDecorators(GetCommandDecorators(), context =>
            {
                var argument = context.ServiceType.GetGenericArguments()[0];
                return argument.Namespace.EndsWith("Commands");
            });

            container.RegisterRequestHandlerDecorators(GetQueryDecorators(), context =>
            {
                var argument = context.ServiceType.GetGenericArguments()[0];
                return argument.Namespace.EndsWith("Queries");
            });

            return container;
        }
Esempio n. 26
0
 // todo: only starting up subscriptions from web client for simplicity, should be done in console app (separate process)
 public void RegisterServices(Container container) {
   container.RegisterSingleton<ResolvedEventPublisher>();
   container.Register<SubscriptionClient[]>(() => {
     // todo: json configuration for subscription clients
     string streamName = "$ce-user";
     string groupName = "user-publisher";
     PersistentSubscriptionSettingsBuilder settings = PersistentSubscriptionSettings.Create()
       .ResolveLinkTos()
       .StartFrom(0)
       .MinimumCheckPointCountOf(1)
       .MaximumCheckPointCountOf(1)
     ;
     try {
       IEventStoreConnection connection = container.GetInstance<Connection.IProvideConnection>().GetConnectionAsync().Result;
       // todo: should not be creating the persistent subscription from code http://docs.geteventstore.com/dotnet-api/3.3.1/competing-consumers/
       connection.CreatePersistentSubscriptionAsync(streamName, groupName, settings, new UserCredentials("admin", "changeit")).Wait();
     } catch (AggregateException ex) when (ex.InnerException.Message.Equals($"Subscription group {groupName} on stream {streamName} already exists")) {
       // subscription already exists
     }
     var userClients = new List<SubscriptionClient>();
     Parallel.ForEach(Enumerable.Range(0, 9), x => {
       userClients.Add(new SubscriptionClient(streamName, groupName,
       container.GetInstance<Connection.IProvideConnection>(), container.GetInstance<ResolvedEventPublisher>()));
     });
     return userClients.ToArray();
   }, Lifestyle.Singleton);
 }
        protected void SetIoC()
		{
			if (Resolver.IsSet)
				return;
			
			var container = new Container();

			//there can be only one
			container.RegisterSingleton<NavigationService>();
			//singletons because they are dependecies for the above singleton
			container.RegisterSingleton<PageService>();

			RegisterPlatformSpecificImplementations (container);

			Resolver.SetResolver (new SimpleInjectorResolver (container));
        }
Esempio n. 28
0
        public static void ConfigContainer(Container container)
        {
            #region - MAPPER -
            var mapperConfig = AutoMapperConfig.GetMapperConfiguration();
            container.RegisterSingleton<IConfigurationProvider>(mapperConfig);
            container.Register(() => mapperConfig.CreateMapper());
            container.Register<IMapperAdapter, AutoMapperAdapter>();
            #endregion

            #region - CONTEXTS -
            container.Register<DbContext, CoreContext>(Lifestyle.Scoped);
            #endregion

            #region - REPOSITORIES -
            container.Register<IClientRepository, ClientRepository>(Lifestyle.Scoped);
            container.Register<IRefreshTokenRepository, RefreshTokenRepository>(Lifestyle.Scoped);
            container.Register<IUsuarioRepository, UsuarioRepository>(Lifestyle.Scoped);
            #endregion

            #region - DOMAINS -
            var registration = Lifestyle.Scoped.CreateRegistration<UsuarioDomain>(container);
            container.AddRegistration(typeof(IUsuarioDomain), registration);
            container.AddRegistration(typeof(IUserStore<Usuario, long>), registration);

            container.Register<UserManager<Usuario, long>>(Lifestyle.Scoped);
            container.Register<IRefreshTokenDomain, RefreshTokenDomain>(Lifestyle.Scoped);
            container.Register<IClientDomain, ClientDomain>(Lifestyle.Scoped);
            container.Register<IAccountDomain, AccountDomain>(Lifestyle.Scoped);
            #endregion
        }
    public void ItShouldGetConsumersFromTheContainer() {
      using (var container = new Container()) {

        var consumerAssemblies = new[] { GetType().Assembly };
        container.Register(typeof(Consumes<>.All), consumerAssemblies);
        var endpointUri = new Uri("loopback://localhost/queue");
        container.RegisterSingleton(() =>
          ServiceBusFactory.New(sbc => {
            sbc.ReceiveFrom(endpointUri);
            sbc.Subscribe(subs => {
              // ReSharper disable AccessToDisposedClosure
              subs.LoadFrom(container);
              // ReSharper restore AccessToDisposedClosure
            });
          }));
        container.Verify();

        var bus = container.GetInstance<IServiceBus>();
        var message = new FakeMessage { Moment = DateTime.Now };
        bus.GetEndpoint(endpointUri).Send(message);

        Thread.Sleep(100);
        Assert.Equal(1, FakeMessage.MessageConsumedCount);
      }
    }
Esempio n. 30
0
        public static void Register(Container container)
        {
            container.Register(typeof (IQueryHandler<,>), new[] {typeof (IQueryHandler<,>).Assembly});
            container.Register(typeof (ICommandHandler<,>), new[] {typeof (ICommandHandler<,>).Assembly});

            container.RegisterCollection(typeof (IHyperMediaState), typeof (IHyperMediaState).Assembly);
            container.Register<IBoardState, BoardState>();
            container.Register<IBoardTaskState, BoardTaskState>();
            container.Register<IBoardColumnState, BoardColumnState>();

            container.Register<ISlugService, SlugService>();

            container.Register<ICommandDispatcher, CommandDispatcher>();
            container.Register<IQueryDispatcher, QueryDispatcher>();
            container.Register<ILinkFactory, LinkFactory>();
            container.Register<IHyperMediaFactory, HyperMediaFactory>();
            container.Register<IMappingService, MappingService>();

            container.RegisterWebApiRequest<IDataContext, DataContext>();

            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
            container.EnableHttpRequestMessageTracking(GlobalConfiguration.Configuration);
            container.RegisterSingleton<IRequestMessageProvider>(new RequestMessageProvider(container));

            container.Register<IValidator<Board>, BoardValidator>();
            container.Register<IValidator<BoardColumn>, BoardColumnValidator>();
            container.Register<IValidator<BoardTask>, BoardTaskValidator>();

            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
        }
Esempio n. 31
0
    /* Managed Extensibility Framework
     * A lot of this is just copy paste code, from http://caliburnmicro.com/documentation/bootstrapper
     * This is used to make whatever we store in our SimpleInjector container available across the application.
     * In this example we have put the windowmanager, EventAggregator and the Data object containing all the data into this container. 
     * The WindowManager manages creation and showing of windows/dialogs/stuff like that. 
     * The EventAggregator is a service that provides us with the ability to publish objects from one entity to another, in a loose fashion. http://caliburnmicro.com/documentation/event-aggregator
     * BingoEvent is a dataobject, that is kept in the container so that all parts of the application might share the same data. 
     * 
     */
    protected override void Configure()
    {
      _container = new Container();

      //Collects values/stuff that has to go in our container
      _container = new Container();
      _container.Register<IWindowManager, WindowManager>();
      _container.RegisterSingleton<IEventAggregator, EventAggregator>();
      _container.RegisterSingleton<BingoEvent, BingoEvent>();
      _container.RegisterSingleton<IDialogCoordinator, DialogCoordinator>();
      //probably not needed? was used to share data/consistent viewmodels, which shouldnt be necessary if application is made well.
      /*var viewModels =
          Assembly.GetExecutingAssembly()
              .DefinedTypes.Where(x => x.GetInterface(typeof(IMainViewItem).Name) != null && !x.IsAbstract && x.IsClass);
      _container.RegisterCollection(typeof(IMainViewItem), viewModels);*/
      _container.Verify();
    }
Esempio n. 32
0
        /// <summary>
        /// DIコンテナの作成
        /// </summary>
        /// <remarks>
        /// 試験で追加のコンテナ登録が必要な場合は、このメソッドをオーバーライドし内部でこのメソッドを呼び出します。
        /// </remarks>
        protected virtual void InitializeContainer(int threadId)
        {
            container = new SimpleInjector.Container();
            container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

            var assemblyParameter = new TestBuildAssemblyParameter();

            assemblyParameter.SetThread(threadId);

            var context = new ApplicationContextImpl(assemblyParameter); // アプリケーションコンテキスト

            context.SetDiContainer(container);

            container.RegisterSingleton <IApplicationContext>(context);
            container.RegisterSingleton <IBuildAssemblyParameter>(assemblyParameter);
            container.Register <ICategoryRepository, CategoryRepository>();
            container.Register <IContentRepository, ContentRepository>();
            container.Register <IFileMappingInfoRepository, FileMappingInfoRepository>();
            container.Register <IWorkspaceRepository, WorkspaceRepository>();
            container.Register <IAppAppMetaInfoRepository, AppAppMetaInfoRepository>();
        }
Esempio n. 33
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>();
        }
Esempio n. 34
0
        public void Register(SimpleInjector.Container container, IConfigurationRoot config)
        {
            container.RegisterSingleton <IAgentStorage, AgentStorage>();
            container.RegisterSingleton <AgentBus>();
            container.RegisterSingleton <WorkflowManager>();


            container.RegisterSingleton(new RedisPubSub(
                                            new RedisConnection(config.GetSection("ConnectionStrings")["RedisServer"])));

            container.RegisterSingleton <ITemplateStorage, TemplateStorage>();
            container.RegisterSingleton <IAgentManager, AgentManager>();
        }
Esempio n. 35
0
        static IMediator BuildMediator()
        {
            var container = new SimpleInjector.Container();

            // Mediator
            container.RegisterSingleton <IMediator, Mediator>();
            container.Register(() => new ServiceFactory(container.GetInstance), Lifestyle.Singleton);

            // Handlers
            var assemblies = new[] { typeof(RequestAsync).Assembly };

            container.Register(typeof(IRequestHandler <,>), assemblies);
            container.Collection.Register(typeof(INotificationHandler <>), assemblies);

            // Pipeline behaviours
            container.Collection.Register(typeof(IPipelineBehavior <,>), new[]
            {
                typeof(GenericPipelineBehavior <,>)
                // optionals can be register in this line.
            });

            // ------ Optionals ------

            // Pre processor
            container.Collection.Append(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>));
            container.Collection.Register(typeof(IRequestPreProcessor <>), new[] { typeof(GenericRequestPreProcessor <>) });

            // Post processor
            container.Collection.Append(typeof(IPipelineBehavior <,>), typeof(RequestPostProcessorBehavior <,>));
            container.Collection.Register(typeof(IRequestPostProcessor <,>), new[] { typeof(GenericRequestPostProcessor <,>) });

            container.Verify();

            var mediator = container.GetInstance <IMediator>();

            return(mediator);
        }
Esempio n. 36
0
        public static Container Initialize()
        {
            container.RegisterConditional(typeof(ILogger),
                                          c => typeof(Log4NetAdapter <>).MakeGenericType(c.Consumer.ImplementationType),
                                          Lifestyle.Singleton,
                                          c => true);

            // App Settings
            container.RegisterSingleton <AppSettings>(createAppSettings);
            var  appSettings            = createAppSettings();
            bool isSqlFormsDataProvider = string.Equals(appSettings.formsDataProvider, "sqlFormsDataProvider", StringComparison.InvariantCultureIgnoreCase);

            // Entity Framework Contexts registration
            container.RegisterSingleton <SitecoreForms>(CreateExperienceFormsDbContext);
            container.RegisterSingleton <SourceMasterDb>(createMasterDbSourceContext);
            container.RegisterSingleton <DestMasterDb>(createMasterDbDestContext);
            if (isSqlFormsDataProvider)
            {
                container.RegisterSingleton <Library.Database.WFFM.WFFM>(CreateWffmDbContext);
            }
            else
            {
                container.RegisterSingleton <MongoAnalytics>(createMongoAnalyticsContext);
            }

            // Metadata Provider
            container.Register <IMetadataProvider, MetadataProvider>();

            // Reporting
            container.Register <IReporter, AnalysisReporter>(Lifestyle.Singleton);

            // Repositories
            container.Register <IDestMasterRepository, DestMasterRepository>(Lifestyle.Singleton);
            container.Register <ISourceMasterRepository, SourceMasterRepository>(Lifestyle.Singleton);
            container.Register <ISitecoreFormsDbRepository, SitecoreFormsDbRepository>(Lifestyle.Singleton);

            container.Register <IFieldFactory, FieldFactory>();
            container.Register <IFieldProvider, FieldProvider>();

            container.Register <IItemConverter, ItemConverter>();
            container.Register <IItemFactory, ItemFactory>();

            container.Register <FormProcessor>();
            container.Register <SubmitConverter>();
            container.Register <FormAppearanceConverter>();
            container.Register <SectionAppearanceConverter>();

            container.Register <DataMigrator>();

            container.Register <MetadataValidator>();
            container.Register <AppSettingsValidator>();
            container.Register <DbConnectionStringValidator>();

            RegisterFormsDataProvider();

            // Configuration to registere unregistered converter types
            container.ResolveUnregisteredType += (sender, e) =>
            {
                if (e.UnregisteredServiceType.IsGenericType &&
                    e.UnregisteredServiceType.GetGenericTypeDefinition() == typeof(BaseFieldConverter))
                {
                    object baseConverter = container.GetInstance(typeof(BaseFieldConverter));

                    // Register the instance as singleton.
                    e.Register(() => baseConverter);
                }
            };

            container.Verify();

            return(container);
        }
Esempio n. 37
0
 public void RegisterSingleton <TConcrete>() where TConcrete : class
 {
     _container.RegisterSingleton <TConcrete>();
 }
Esempio n. 38
0
        public Container(ControllerOptions options)
        {
            _options = options ?? throw new ArgumentNullException(nameof(options));

            _container.RegisterSingleton(options);
        }
Esempio n. 39
0
        /// <summary>
        /// Registers the instance used types defined in Export, ExportScope, InheritedExport and InheritiedExportScope attributes
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="instance">The instance.</param>
        public static void RegisterSingletonInstance(this Container container, object instance)
        {
            var type = instance.GetType();

            container.RegisterSingleton(type, instance);
        }