public static void RegisterServices(Container container, ILoggerFactory loggerFactory) {
            container.RegisterSingleton<ILoggerFactory>(loggerFactory);
            container.RegisterSingleton(typeof(ILogger<>), typeof(Logger<>));

            ServiceProvider.Current = container;
            container.RegisterSingleton<ISerializer>(() => new JsonNetSerializer());

            var metricsClient = new InMemoryMetricsClient();
            container.RegisterSingleton<IMetricsClient>(metricsClient);
            container.RegisterSingleton<ICacheClient, InMemoryCacheClient>();

            container.RegisterCollection(typeof(IQueueBehavior<ValuesPost>), new[] {
                Lifestyle.Singleton.CreateRegistration(
                    () => new MetricsQueueBehavior<ValuesPost>(metricsClient), container)
            });
            container.RegisterSingleton<IQueue<ValuesPost>>(() => new InMemoryQueue<ValuesPost>(behaviors: container.GetAllInstances<IQueueBehavior<ValuesPost>>()));
            
            container.RegisterCollection(typeof(IQueueBehavior<WorkItemData>), new[] {
                Lifestyle.Singleton.CreateRegistration(
                    () => new MetricsQueueBehavior<WorkItemData>(metricsClient), container)
            });

            var handlers = new WorkItemHandlers();
            handlers.Register<DeleteValueWorkItem, DeleteValueWorkItemHandler>();
            container.RegisterSingleton(handlers);

            container.RegisterSingleton<IQueue<WorkItemData>>(() => new InMemoryQueue<WorkItemData>(behaviors: container.GetAllInstances<IQueueBehavior<WorkItemData>>(), workItemTimeout: TimeSpan.FromHours(1)));
            
            container.RegisterSingleton<IMessageBus, InMemoryMessageBus>();
            container.RegisterSingleton<IMessagePublisher>(container.GetInstance<IMessageBus>);
            container.RegisterSingleton<IMessageSubscriber>(container.GetInstance<IMessageBus>);

            container.RegisterSingleton<ILockProvider, CacheLockProvider>();
            container.RegisterSingleton<IFileStorage>(new InMemoryFileStorage());
        }
Beispiel #2
0
        public void RegisterSingletonCollection <TItem>(IEnumerable <TItem> items) where TItem : class
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            _container.RegisterCollection(items);
        }
        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;
        }
Beispiel #4
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);
        }
        private void PopulateProviderCache()
        {
            if (this.Providers == null)
            {
                this.Providers = new Dictionary<string, IAuditDbProvider>();
            }

            string providerDirectory = AppDomain.CurrentDomain.BaseDirectory;

            var providerAssemblies =
                from file in new DirectoryInfo(providerDirectory).GetFiles()
                where file.Extension.ToLower() == ".dll"
                select Assembly.LoadFile(file.FullName);

            Container container = new Container();

            var providerTypes = container.GetTypesToRegister(typeof(IAuditDbProvider), providerAssemblies);

            container.RegisterCollection<IAuditDbProvider>(providerTypes);

            foreach (var provider in container.GetAllInstances<IAuditDbProvider>())
            {
                Providers.Add(provider.ProviderNamespace.ToLowerInvariant(),provider);
            }
        }
        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);
        }
Beispiel #7
0
        public static void UseSerialization(this Container services)
        {
            services.RegisterCollection(typeof(ICustomJsonMapper <>), typeof(ICustomJsonMapper <>).Assembly);
            services.Register(typeof(IMapperTypeRetriever <>), new [] { typeof(IMapperTypeRetriever <>).Assembly });

            services.RegisterCollection(typeof(JsonConverterBase), typeof(JsonConverterBase).Assembly);

            services.Register(typeof(IDecoratorTypeRetriever <>), new [] { typeof(IMapperTypeRetriever <>).Assembly });

            services.Register <DeserializationContractResolver>(Lifestyle.Singleton);
            services.Register <SerializationContractResolver>(Lifestyle.Singleton);
            services.Register <IModelValidator, NullModelValidator>(Lifestyle.Singleton);
            services.Register <JsonSerializerSettingsFactory>(Lifestyle.Singleton);
            services.Register <ISerializerService, SerializerService>(Lifestyle.Singleton);
            services.Register <ISerializationConfiguration, SerializationConfiguration>(Lifestyle.Singleton);
        }
Beispiel #8
0
        private static IDictionary <string, IHttpClientBuilder> UseMultipleClients(this Container services, IConfiguration configuration, IDictionary <string, TokenFlow> clients)
        {
            var collection = new ServiceCollection();

            services.UseHttpApiDefaults();

            var builders       = new ConcurrentDictionary <string, IHttpClientBuilder>();
            var clientBuilders = new List <Registration>();

            foreach (KeyValuePair <string, TokenFlow> client in clients)
            {
                string    clientName = client.Key;
                TokenFlow tokenFlow  = client.Value;

                IClientConfiguration clientConfiguration = configuration.GetSection(clientName).Get <ClientConfiguration>();
                Validator.ValidateObject(clientConfiguration, new ValidationContext(clientConfiguration), true);

                builders.TryAdd(clientName, services.SetupClient(collection, clientName, clientConfiguration, tokenFlow));

                clientBuilders.Add(Lifestyle.Singleton.CreateRegistration(() => new CtpClient(collection.BuildServiceProvider().GetService <IHttpClientFactory>(), services.GetService <IHttpApiCommandFactory>(), services.GetService <ISerializerService>(), services.GetService <IUserAgentProvider>())
                {
                    Name = clientName
                }, services));
            }
            services.RegisterCollection <IClient>(clientBuilders);

            collection.AddHttpClient(DefaultClientNames.Authorization);
            services.UseTokenProviders(collection.BuildServiceProvider().GetService <IHttpClientFactory>());

            return(builders);
        }
        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;
        }
Beispiel #10
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 RegisterPlugins <TImplements, TExport>(this Container container,
                                                                  IEnumerable <Assembly> assemblies, Lifestyle lifestyle = null) where TExport : class
        {
            var pluginTypes = GetTypes <TImplements>(assemblies).ToArray();

            HandleLifestyle <TExport>(container, lifestyle, pluginTypes);
            container.RegisterCollection <TExport>(pluginTypes);
        }
        internal static Container BuildMediator()
        {
            var container = new Container();
            var assemblies = GetAssemblies().ToArray();
            container.RegisterSingleton<IMediator, Mediator>();
            container.Register(typeof(IRequestHandler<,>), assemblies);
            container.Register(typeof(IAsyncRequestHandler<,>), assemblies);
            container.RegisterCollection(typeof(INotificationHandler<>), assemblies);
            container.RegisterCollection(typeof(IAsyncNotificationHandler<>), assemblies);
            container.RegisterSingleton(Console.Out);
            container.RegisterSingleton(new SingleInstanceFactory(container.GetInstance));
            container.RegisterSingleton(new MultiInstanceFactory(container.GetAllInstances));

            container.Verify();

            return container;
        }
Beispiel #13
0
        public static void Setup()
        {
            var container = new Container();
            var perRequest = new WebRequestLifestyle();
            var dataAccessAssembly = typeof(CinemaContext).Assembly;
            var moviesAssembly = typeof(Seat).Assembly;
            var promotionsAssembly = typeof(Promotions.Promotion).Assembly;
            var applicationAssembly = typeof(RenamePromotionCommand).Assembly;
            var connectionString = ConfigurationManager.ConnectionStrings["DDDCinema"].ConnectionString;

            container.Register(() => new CinemaContext(connectionString), perRequest);
            container.Register(() => new PromotionsContext(connectionString), perRequest);
            container.Register(() => new InfrastructureContext(connectionString), perRequest);
            container.Register(() => new DDDCinemaReadonly(), perRequest);
            var userProviderRegistration = Lifestyle.Singleton.CreateRegistration<ContextUserProvider>(container);
            container.AddRegistration(typeof(ICurrentUserProvider), userProviderRegistration);
            container.AddRegistration(typeof(ContextUserProvider), userProviderRegistration);
            container.Register<IWinChanceCalculatorFactory, SimpleInjectorWinChanceCalculatorFactory>(Lifestyle.Singleton);

            foreach (var repositorType in dataAccessAssembly.GetExportedTypes()
                .Where(t => t.Name.Contains("Repository")))
            {
                container.Register(repositorType.GetInterfaces().Single(), repositorType, perRequest);
            }

            container.RegisterDecorator(typeof(ICommandHandler<LoginCommand>), typeof(AuditingLoginCommandHandler));
            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(AuditingCommandHandler<>),
                p => !p.AppliedDecorators.Any(t => t.Name.Contains("Auditing")));
            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(CinemaTransactionalCommandHandler<>));
            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(PromotionTransactionalCommandHandler<>));
            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(InfrastructureTransactionalCommandHandler<>));
            container.Register(typeof(ICommandHandler<>), new[] { applicationAssembly });

            container.RegisterCollection(typeof(INotificationSender), new[] { moviesAssembly });
            var registration = perRequest.CreateRegistration<SendNotificationWhenSeatTaken>(container);
            container.AppendToCollection(typeof(IDomainEventHandler<>), typeof(AuditOccurrenceEventHandler<>));
            container.RegisterCollection(typeof(IDomainEventHandler<>), moviesAssembly, promotionsAssembly);
            container.RegisterDecorator(typeof(IDomainEventHandler<>), typeof(AuditingEventHandler<>),
                p => !p.ImplementationType.Name.Contains("Audit"));

            container.Register<List<INotificationSender>>(() => container.GetAllInstances<INotificationSender>().ToList(), perRequest);
            container.Register<ISheduler, SagaTimeoutSheduler>(perRequest);
            container.Register<IPromotionCodeGenerator, PromoCodeGenerator>(perRequest);
            DomainEventBus.Current = new SimpleInjectorEventBus(container);
            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
        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;
        }
Beispiel #15
0
 private static Container GetRegisteredContainer()
 {
     SimpleInjector.Container container = new SimpleInjector.Container();
     container.Register <IDependencyOne, DependencyOne>();
     container.Register <IDependencyTwo, DependencyTwo>();
     container.Register <IDependencyThree, DependencyThree>();
     container.Register <IProcessorFactory, ProcessorFactory>();
     container.RegisterCollection <IProcessor>(new Assembly[] { Assembly.GetExecutingAssembly() });
     return(container);
 }
Beispiel #16
0
        public void Configuration(IAppBuilder app)
        {
            var mapperConfig = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile<FieldProfile>();
                cfg.AddProfile<ArchiveProfile>();
                cfg.AddProfile<RecordProfile>();
                cfg.AddProfile<SectionProfile>();
                cfg.AddProfile<BatchProfile>();
                cfg.AddProfile<CollectionProfile>();
                cfg.AddProfile<OptionProfile>();
            });
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
            container.Register<IAPContext>(Lifestyle.Scoped);
            container.RegisterSingleton(mapperConfig.CreateMapper());
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

            // MEDIATR ---------------------------------------------------------------------
            var assemblies = GetAssemblies().ToArray();
            container.RegisterSingleton<IMediator, Mediator>();
            container.Register(typeof(IRequestHandler<,>), assemblies);
            container.Register(typeof(IAsyncRequestHandler<,>), assemblies);
            container.RegisterCollection(typeof(INotificationHandler<>), assemblies);
            container.RegisterCollection(typeof(IAsyncNotificationHandler<>), assemblies);
            container.RegisterSingleton(Console.Out);
            container.RegisterSingleton(new SingleInstanceFactory(container.GetInstance));
            container.RegisterSingleton(new MultiInstanceFactory(container.GetAllInstances));
            // ------------------------------------------------------------------------------

            container.Verify();
            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);

            HttpConfiguration config = new HttpConfiguration()
            {
                DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container)
            };
            ConfigureOAuth(app);
            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }
 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());
 }
 private static void UseHttpApiDefaults(this Container services)
 {
     services.Register <ITokenStoreManager, InMemoryTokenStoreManager>(Lifestyle.Transient);
     services.Register <IUserCredentialsStoreManager, InMemoryUserCredentialsStoreManager>(Lifestyle.Transient);
     services.Register <IAnonymousCredentialsStoreManager, InMemoryAnonymousCredentialsStoreManager>(Lifestyle.Transient);
     services.RegisterCollection(typeof(IRequestMessageBuilder), typeof(IRequestMessageBuilder).Assembly);
     services.RegisterCollection(typeof(IAdditionalParametersBuilder), typeof(IAdditionalParametersBuilder).Assembly);
     services.RegisterCollection(typeof(ISearchParametersBuilder), typeof(ISearchParametersBuilder).Assembly);
     services.RegisterCollection(typeof(IQueryParametersBuilder), typeof(IQueryParametersBuilder).Assembly);
     services.RegisterCollection(typeof(IUploadImageParametersBuilder), typeof(IUploadImageParametersBuilder).Assembly);
     services.RegisterSingleton <ILoggerFactory>(new LoggerFactory());
     services.Register <IEndpointRetriever, EndpointRetriever>(Lifestyle.Singleton);
     services.Register <IParametersBuilderFactory <IAdditionalParametersBuilder>, ParametersBuilderFactory <IAdditionalParametersBuilder> >(Lifestyle.Singleton);
     services.Register <IParametersBuilderFactory <ISearchParametersBuilder>, ParametersBuilderFactory <ISearchParametersBuilder> >(Lifestyle.Singleton);
     services.Register <IParametersBuilderFactory <IQueryParametersBuilder>, ParametersBuilderFactory <IQueryParametersBuilder> >(Lifestyle.Singleton);
     services.Register <IParametersBuilderFactory <IUploadImageParametersBuilder>, ParametersBuilderFactory <IUploadImageParametersBuilder> >(Lifestyle.Singleton);
     services.Register <IHttpApiCommandFactory, HttpApiCommandFactory>(Lifestyle.Singleton);
     services.Register <IRequestMessageBuilderFactory, RequestMessageBuilderFactory>(Lifestyle.Singleton);
     services.Register <IUserAgentProvider, UserAgentProvider>(Lifestyle.Singleton);
     services.Register <ITokenSerializerService, TokenSerializerService>(Lifestyle.Singleton);
 }
Beispiel #19
0
        public static Container Compose()
        {
            var container = new Container();

            container.Register(typeof(INetlinkServiceBusMessage), typeof(NetlinkPointNotificationMessage));
            container.Register(typeof(IServiceBusQueueNameFactory), typeof(QueueNameFactory));
            container.Register(typeof(IServiceBusConnectionStringFactory), typeof(ConnectionStringFactory));
            container.Register(
                typeof (
                    IServiceBusClient
                        <IServiceBusQueueNameFactory, IServiceBusConnectionStringFactory,
                            INetlinkServiceBusMessage>), typeof (AzureStorageQueueClient));

            container.Register(typeof(IRuleEngineFactory<>), typeof(BooleanRuleEngineFactory));
            container.Register(typeof(IRuleEngineFactory<>), typeof(IntegerRuleEngineFactory));
            container.Register(typeof(IRuleEngineFactory<>), typeof(DoubleRuleEngineFactory));
            container.RegisterCollection(typeof(IRuleExecutionResponse), AppDomain.CurrentDomain.GetAssemblies());
            container.RegisterCollection(typeof(IPreRuleHandler<>), AppDomain.CurrentDomain.GetAssemblies());
            container.RegisterCollection(typeof(IRuleHandler<,>), AppDomain.CurrentDomain.GetAssemblies());
            container.RegisterCollection(typeof(IPostRuleHandler<,>), AppDomain.CurrentDomain.GetAssemblies());
            container.RegisterCollection(typeof(IRuleExecutor), AppDomain.CurrentDomain.GetAssemblies());
            container.RegisterCollection(typeof(IRuleFactory<>), AppDomain.CurrentDomain.GetAssemblies());

            container.RegisterDecorator(typeof(IRuleHandler<,>), typeof(RuleMediatorPipeline<,>));

            container.Verify(VerificationOption.VerifyAndDiagnose);

            return container;
        }
Beispiel #20
0
        public void Register <TInterface>(Func <IContainer, TInterface> factory, Contracts.Lifestyle lifestyle, string name = null) where TInterface : class
        {
            if (_child)
            {
                return;
            }

            // Trick to accomplish what named instances are meant to - registering multiple of the same interface.
            if (!string.IsNullOrEmpty(name))
            {
                if (!_namedCollections.ContainsKey(typeof(TInterface)))
                {
                    _namedCollections[typeof(TInterface)] = new List <SimpleInjector.Registration>();
                }

                _namedCollections[typeof(TInterface)].Add(ConvertLifestyle(lifestyle).CreateRegistration <TInterface>(() => factory(this), _container));

                _container.RegisterCollection <TInterface>(_namedCollections[typeof(TInterface)]);
                return;
            }
            _container.Register(() => factory(this), ConvertLifestyle(lifestyle));
        }
        public static void ConfigureRemarks(Container container)
        {
            var assembly = typeof(ClaimedRemark).Assembly;

            var types = from type in assembly.GetTypes()
                        where (typeof(Remark).IsAssignableFrom(type))
                        where type.IsClass
                        select type;

            if (!types.Any()) return;

            container.RegisterCollection(typeof(Remark), types);
        }
Beispiel #22
0
        static Container Bootstrap()
        {
            Container container = new Container();
            container.RegisterCollection(typeof(IAdapter), new[] { typeof(IAdapter).Assembly });
            Settings settings = new Settings();
            settings.ConnectionString = ConfigurationManager.ConnectionStrings["AdventureWorks2014"].ConnectionString;

            container.RegisterSingleton<Settings>(settings);
            container.Register<PerformaceTester>(Lifestyle.Transient);

            container.Verify();

            return container;
        }
Beispiel #23
0
        public void RegisterServices(Container container, CompositionRootSettings settings)
        {
            if (settings.EventAssemblies == null) return;

            container.RegisterSingleton<IProcessEvents, EventProcessor>();

            container.RegisterCollection(typeof(IHandleEvent<>), settings.EventAssemblies);

            container.Register(typeof(ITriggerEvent<>), typeof(MultipleDispatchEventTrigger<>));

            container.RegisterDecorator(
                typeof(ITriggerEvent<>),
                typeof(TriggerEventWhenHandlersExistDecorator<>)
            );
        }
Beispiel #24
0
        /// <summary>
        /// Entry-level example of configuring the message bus and working with messages: sending, handling, pub-sub
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //Setup Simple Injector for handlers
            _container = new Container();

            _container.RegisterCollection(typeof(IMessageConsumer<>), new[] {typeof(Program).Assembly});

            _container.Verify();

            //NLog.Config.SimpleConfigurator.ConfigureForConsoleLogging(NLog.LogLevel.Warn);
            //uncomment only one example at a time
            //TestSendReply();
            TestSeq();
            //TestPubSub(); //run pub-sub example
            // TestStaticRouting(); //static routing example
        }
        private static void UseTokenProviders(this Container services, IHttpClientFactory factory)
        {
            var providers = new List <Registration>
            {
                Lifestyle.Transient.CreateRegistration(
                    () => new AnonymousSessionTokenProvider(factory,
                                                            services.GetService <IAnonymousCredentialsStoreManager>(),
                                                            services.GetService <ITokenSerializerService>()), services),
                Lifestyle.Transient.CreateRegistration(
                    () => new ClientCredentialsTokenProvider(factory, services.GetService <ITokenStoreManager>(),
                                                             services.GetService <ITokenSerializerService>()), services),
                Lifestyle.Transient.CreateRegistration(
                    () => new PasswordTokenProvider(factory, services.GetService <IUserCredentialsStoreManager>(),
                                                    services.GetService <ITokenSerializerService>()), services)
            };

            services.RegisterCollection <ITokenProvider>(providers);
        }
        // Private Helpers
        private static void RegisterByConvention(Container container, AssemblyFilter assemblyFilter, Convention implementationFilter, Convention decoratorFilter, Lifestyle lifestyle)
        {
            var types = GetAllLoadedTypes(assemblyFilter);

            var registrations = from service in types
                                let implementations = from implementation in types
                                                      where implementation.IsConcreteTypeThatImplements(service)
                                                         && implementationFilter(service, implementation)
                                                      select implementation
                                let decorators = from decorator in types
                                                 where decorator.IsConcreteTypeThatImplements(service)
                                                    && decoratorFilter(service, decorator)
                                                 select decorator
                                where service.IsInterface
                                   && !container.HasAlreadyRegistered(service)
                                select new
                                {
                                    Service = service,
                                    Implementations = implementations,
                                    Decorators = decorators
                                };

            foreach (var registration in registrations)
            {
                if (registration.Implementations.Count() == 1)
                {
                    container.Register(registration.Service, registration.Implementations.First(), lifestyle);
                }
                else if (registration.Implementations.Count() > 1)
                {
                    container.RegisterCollection(registration.Service, registration.Implementations);
                }

                foreach (var decorator in registration.Decorators)
                {
                    container.RegisterDecorator(registration.Service, decorator);
                }
            }
        }
        private static void ConfigureMediatr(Container container)
        {
            var assemblies = new[] { typeof(Startup).Assembly };
            container.Register<IMediator, Mediator>(Lifestyle.Singleton);
            container.RegisterSingleton(new SingleInstanceFactory(container.GetInstance));
            container.RegisterSingleton(new MultiInstanceFactory(container.GetAllInstances));

            container.Register(typeof(IRequestHandler<,>), assemblies, Lifestyle.Scoped);
            container.Register(typeof(IAsyncRequestHandler<,>), assemblies, Lifestyle.Scoped);
            container.RegisterDecorator(typeof(IAsyncRequestHandler<,>), typeof(AsyncValidatorHandler<,>), Lifestyle.Scoped);

            container.RegisterCollection(typeof(INotificationHandler<>), assemblies);
            container.RegisterCollection(typeof(IAsyncNotificationHandler<>), assemblies);
        }
Beispiel #28
0
 public void RegisterServices(Container container) {
   container.RegisterSingleton(typeof(IPublishEvent), typeof(ImmediatelyConsistentEventPublisher));
   container.RegisterCollection(typeof(IHandleEvent<>), HandlerAssemblies);
 }
        public static void ConfigureValidators(Container container)
        {
            container.Register(typeof(IValidator<>),
                new[] { typeof(SaveEmployeeValidator).Assembly });

            var repositoryAssembly = typeof(SaveEmployeeValidator).Assembly;

            var requests =
                from type in repositoryAssembly.GetExportedTypes()
                where type.Namespace.Contains("Patterns.Api.Requests")
                select type;

            foreach (var request in requests)
            {
                var taskTypes = from type in repositoryAssembly.GetTypes()
                                where typeof(IValidator<>).MakeGenericType(request).IsAssignableFrom(type)
                                      && !type.IsAbstract && !type.IsGenericTypeDefinition
                                select type;

                if (!taskTypes.Any()) continue;

                taskTypes.ForEach(type => container.Register(type, type, Lifestyle.Transient));

                // registers a list of all those (singleton) tasks.
                var handler = typeof(IValidator<>).MakeGenericType(request);
                container.RegisterCollection(handler, taskTypes);
            }
        }
        public static IServiceProvider UseSimpleInjector(this IServiceCollection services)
        {
            var container = new Container();
            var scopeFactory = new SimpleInjectorServiceScopeFactory(container);

            container.Options.AllowOverridingRegistrations = true;
            container.Options.ResolveUnregisteredCollections = true;
            container.Options.SuppressLifestyleMismatchVerification = true;
            container.Options.DefaultScopedLifestyle = scopeFactory;

            foreach (var descriptor in services)
            {
                //if (descriptor.ServiceType.FullName.IndexOf("IConfigureOptions") >= 0)
                //{
                //    System.Diagnostics.Debugger.Break();
                //}

                var lifetime = ConvertLifetimeToSimpleInjectorLifetime(descriptor.Lifetime);

                if (descriptor.ImplementationType != null)
                {
                    var serviceTypeInfo = descriptor.ServiceType.GetTypeInfo();

                    if (serviceTypeInfo.IsGenericTypeDefinition)
                    {
                        if (descriptor.ImplementationType.GetTypeInfo().IsGenericTypeDefinition)
                        {
                            // How do you pass the lifetime here?
                            container.Register(descriptor.ServiceType, descriptor.ImplementationType, lifetime);
                        }
                        else
                        {
                            container.Register(descriptor.ServiceType, new[] { descriptor.ImplementationType }, lifetime);
                        }
                    }
                    else
                    {
                        container.Register(descriptor.ServiceType, descriptor.ImplementationType, lifetime);

                        // for collection based
                        container.Register(descriptor.ImplementationType, descriptor.ImplementationType, lifetime);
                    }
                }
                else if (descriptor.ImplementationFactory != null)
                {
                    container.Register(
                        descriptor.ServiceType,
                        () => descriptor.ImplementationFactory(container.GetService<IServiceProvider>()),
                        lifetime);
                }
                else
                {
                    container.Register(
                        descriptor.ServiceType,
                        () => descriptor.ImplementationInstance,
                        lifetime);
                }
            }

            var groupedTypes = services
                .GroupBy(s => s.ServiceType);

            foreach (var groupedType in groupedTypes)
            {
                var serviceType = groupedType.Key;
                var type = typeof(IEnumerable<>).MakeGenericType(serviceType);

                if (serviceType.GetTypeInfo().IsGenericTypeDefinition)
                {
                    container.RegisterCollection(serviceType, groupedType.Select(t => t.ImplementationType));
                }
                else
                {
                    // TODO: Get longest lifestyle?
                    var lifetime = ConvertLifetimeToSimpleInjectorLifetime(groupedType.First().Lifetime);

                    container.Register(
                        type,
                        () =>
                        {
                            var collectionServices = groupedType
                                .Where(c => c.ImplementationType != null)
                                .Select(c => container.GetRequiredService(c.ImplementationType));

                            return typeof(System.Linq.Enumerable)
                                    .GetMethod("Cast", new[] { typeof(System.Collections.IEnumerable) })
                                    .MakeGenericMethod(groupedType.Key)
                                    .Invoke(null, new object[] { collectionServices });
                        },
                        lifetime);
                }
            }

            container.Register<IServiceProvider>(() => container, Lifestyle.Singleton);
            container.Register<IServiceScopeFactory>(() => scopeFactory, Lifestyle.Singleton);

            // container.Verify();

            return container;
        }
 private static void ConfigureFluentValidator(Container container)
 {
     var assemblies = new[] { typeof(Startup).Assembly };
     container.RegisterCollection(typeof(IValidator<>), assemblies);
     container.Register(typeof(IValidator<>), typeof(CompositeValidator<>), Lifestyle.Singleton);
 }
Beispiel #32
0
 public static void UseValidation(this Container services)
 {
     services.Options.AllowOverridingRegistrations = true;
     services.RegisterCollection(typeof(IResourceValidator), typeof(IResourceValidator).Assembly);
     services.Register <IModelValidator, ModelValidator>(Lifestyle.Singleton);
 }
Beispiel #33
0
        public void RegisterServices(Container container)
        {
            //Config
            container.Register<IDbSettings>(() => new DbSettings(Constants.ConnectionName));
            container.Register<IApiAuthenticationSettings>(
                () => (ApiAuthenticationSettings) (dynamic) ConfigurationManager.GetSection("apiSecuritySettings"));
            container.Register<IExternalServicesSettings>(
                () => (ExternalServicesSettings)(dynamic)ConfigurationManager.GetSection("externalServicesSettings"));
            container.Register<ILetMeServiceEndpoints>(
                () => (LetMeServiceEndpoints)(dynamic)ConfigurationManager.GetSection("letMeServiceEndpoints"));
            container.Register<ILetMeServiceUrlSettings>(
                () => (LetMeServiceUrlSettings)(dynamic)ConfigurationManager.GetSection("letMeServiceUrls"));

            //Utils
            container.Register<ILogger, Log4NetLogger>();

            //Pipelines
            container.Register<IPipeline<SubscriberRecord>, SubscriberPipeline>();

            //Builders
            container.Register<ITraitBuilder, TraitBuilder>();

            //Services
            container.Register<IRestService, RestService>();
            container.Register<ICampaignService, CampaignService>();
            container.Register<IPropertyService, PropertyService>();
            container.Register<IApplicationService, ApplicationService>();
            container.Register<IEventLogService, EventLogService>();
            container.Register<ISegmentService, SegmentService>();
            container.Register<ISubscriberRecordService, SubscriberRecordService>();
            container.Register<ISubscriberService, SubscriberService>();
            container.Register<ISubscriberTrackingService<ApplicationSummary>, ApplicationSummarySubscriberTrackingService>();
            container.Register<ISubscriberTrackingService<LandlordSummary>, LandlordSummarySubscriberTrackingService>();
            container.Register<IShortUrlService, ShortUrlService>();
            container.Register<ILandlordService, LandlordService>();

            //Providers
            container.Register<IApplicationProvider, ApplicationProvider>();
            container.Register<IPropertyProvider, PropertyProvider>();
            container.Register<IShortUrlProvider, ShortUrlProvider>();
            container.Register<ILandlordProvider, LandlordProvider>();
            container.Register<ISegmentProvider, SegmentProvider>();

            //Repositories
            container.Register<ICampaignRepository, EventRepository>();
            container.Register<ISubscriberRecordRepository, SubscriberRecordRepository>();

            //Factories
            container.Register<IDataGatherFactory<ApplicationSummary>, ApplicationGatherFactory>();
            container.Register<IDataGatherFactory<LandlordSummary>, LandlordGatherFactory>();
            container.Register<ICampaignLogicFactory, CampaignLogicFactory>();
            container.Register<IIdentityLogicFactory, IdentityLogicFactory>();
            container.Register<ISubscriberStateFactory, SubscriberStateFactory>();
            container.Register<ITrackLogicFactory, TrackLogicFactory>();

            container.RegisterCollection(typeof(ISubscriberState), new[]
            {
              typeof(HasGuarantorSubscriberState)  
            });

            //Handlers
            container.Register<ICampaignHandler, CampaignHandler>();

            container.Register<IAutoMessagingContext>(
                () => new AutoMessagingContext(container.GetInstance<IDbSettings>()));

            container.Verify();
        }