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 void RegisterServices(Container container, CompositionRootSettings settings) { if (settings.TransactionAssemblies == null) return; container.Register<IProcessQueries, QueryProcessor>(Lifestyle.Singleton); container.Register(typeof (IHandleQuery<,>), settings.TransactionAssemblies); container.RegisterDecorator( typeof(IHandleQuery<,>), typeof(QueryEventProcessingDecorator<,>), c => { var attribute = c.ImplementationType.GetCustomAttribute<RaiseEventAttribute>(); return attribute != null && attribute.Enabled; } ); container.RegisterDecorator( typeof (IHandleQuery<,>), typeof (ValidateQueryDecorator<,>) ); container.RegisterDecorator( typeof (IHandleQuery<,>), typeof (QueryLifetimeScopeDecorator<,>), Lifestyle.Singleton ); container.RegisterDecorator( typeof (IHandleQuery<,>), typeof (QueryNotNullDecorator<,>), Lifestyle.Singleton ); }
public static Container AddCommandsValidation(this Container container) { container.RegisterDecorator(typeof(IAsyncCommandHandler <>), typeof(ValidateAsyncCommandDecorator <>), Lifestyle.Transient); container.RegisterDecorator(typeof(IAsyncCommandHandler <,>), typeof(ValidateAsyncCommandDecorator <,>), Lifestyle.Transient); container.RegisterDecorator(typeof(ICommandHandler <>), typeof(ValidateCommandDecorator <>), Lifestyle.Transient); container.RegisterDecorator(typeof(ICommandHandler <,>), typeof(ValidateCommandDecorator <,>), Lifestyle.Transient); return(container); }
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; }
public RegisterDecoratorLifestyleNonGeneric() { var container = new Container(); container.RegisterDecorator(typeof(ICommon), typeof(CommonImpl1), Lifestyle.CreateHybrid(() => true, Lifestyle.Transient, Lifestyle.Singleton)); }
public static void Bootstrap(Container container) { if (container == null) { throw new ArgumentNullException(nameof(container)); } container.RegisterSingleton<IValidator>(new DataAnnotationsValidator(container)); container.Register(typeof(ICommandHandler<>), businessLayerAssemblies); container.RegisterDecorator(typeof(ICommandHandler<>), typeof(ValidationCommandHandlerDecorator<>)); container.RegisterDecorator(typeof(ICommandHandler<>), typeof(AuthorizationCommandHandlerDecorator<>)); container.Register(typeof(IQueryHandler<,>), businessLayerAssemblies); container.RegisterDecorator(typeof(IQueryHandler<,>), typeof(AuthorizationQueryHandlerDecorator<,>)); }
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 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; }
public static void Bootstrap(Container container) { if (container == null) { throw new ArgumentNullException("container"); } container.RegisterSingle<IValidator>(new DataAnnotationsValidator(container)); container.RegisterManyForOpenGeneric(typeof(ICommandHandler<>), Assembly.GetExecutingAssembly()); container.RegisterDecorator(typeof(ICommandHandler<>), typeof(ValidationCommandHandlerDecorator<>)); container.RegisterDecorator(typeof(ICommandHandler<>), typeof(AuthorizationCommandHandlerDecorator<>)); container.RegisterManyForOpenGeneric(typeof(IQueryHandler<,>), Assembly.GetExecutingAssembly()); container.RegisterDecorator(typeof(IQueryHandler<,>), typeof(AuthorizationQueryHandlerDecorator<,>)); }
public RegisterDecoratorLifestylePredicateNonGeneric() { var container = new Container(); var custom = Lifestyle.CreateCustom("custom", transientInstanceCreator => () => transientInstanceCreator()); container.RegisterDecorator(typeof(ICommon), typeof(CommonImpl1), custom, context => true); }
public void RegisterServices(Container container) { container.Register(() => new SmtpClient(), Lifestyle.Singleton); container.Register<IDeliverEmail, DeliverEmail>(Lifestyle.Singleton); container.RegisterDecorator( typeof(IDeliverEmail), typeof(DeliverEmailAsynchronouslyProxyDecorator), Lifestyle.Singleton ); }
public SimpleInjectorContainer Setup(IConfiguration configuration) { var container = new SimpleInjectorContainer(); container.Register <IMyLogger, MyLogger>(Lifestyle.Singleton); // Humble Objects replacing Functions container.Register <ReceiveCreateTicket>(); container.Register <ReceiveGetTicket>(); container.Register <ReceiveGetTickets>(); container.Register <ReceiveGetTicketMediator>(); container.Register <ReceiveGetTicketsMediator>(); container.Register <ITicketRepository, TicketRepository>(Lifestyle.Singleton); container.Register <ITicketAuditRepository, TicketAuditRepository>(Lifestyle.Singleton); // Inject time to remove impurity container.Register <ITimeProvider, TimeProvider>(Lifestyle.Singleton); // Cannot inject IUserContext in Function App var assembly = typeof(ITimeProvider).Assembly; // Commands container.Register(typeof(ICommandService <>), assembly); // Decorators can be applied conditionally with type constraints https://simpleinjector.readthedocs.io/en/latest/aop.html#decoration container.RegisterDecorator(typeof(ICommandService <>), typeof(AuditCommandServiceDecorator <>)); container.RegisterDecorator(typeof(ICommandService <>), typeof(DeadlockRetryCommandServiceDecorator <>)); container.RegisterDecorator(typeof(ICommandService <>), typeof(TransactionCommandServiceDecorator <>)); container.RegisterDecorator(typeof(ICommandService <>), typeof(LogCommandServiceDecorator <>)); // Events container.Register <ILocationService, LocationService>(Lifestyle.Singleton); container.Register <IInventoryManagement, InventoryManagement>(Lifestyle.Singleton); container.Register(typeof(IEventHandler <>), typeof(IEventHandler <>).Assembly); // Simple Queries container.Register <IQueryTicket, QueryTicket>(Lifestyle.Singleton); container.Register <IQueryTickets, QueryTickets>(Lifestyle.Singleton); container.RegisterDecorator(typeof(IQueryTickets), typeof(QueryTicketsCachedDecorator), Lifestyle.Singleton); // Query Mediator container.Register <IQueryProcessor, QueryProcessor>(Lifestyle.Singleton); container.Register(typeof(IQueryHandler <,>), typeof(IQueryHandler <,>).Assembly); container.RegisterDecorator(typeof(IQueryHandler <,>), typeof(PerformanceLogQueryHandlerDecorator <,>)); container.RegisterDecorator(typeof(IQueryHandler <,>), typeof(ValidationQueryHandlerDecorator <,>)); container.RegisterDecorator(typeof(IQueryHandler <,>), typeof(LogQueryHandlerDecorator <,>)); container.Verify(); return(container); }
private static void InitializeContainer(Container container) { container.RegisterPerWebRequest<IDbConnection>(CreateConnection); container.RegisterSingle<Logger>(); container.Register<IDbCommand>(() => new SqlCommand(string.Empty,container.GetInstance<IDbConnection>() as SqlConnection)); container.RegisterPerWebRequest<IContactRepository, ContactRepository>(); //container.RegisterManyForOpenGeneric(typeof(ICommandHandler<>), typeof(Contact).Assembly); container.RegisterPerWebRequest<ICommandHandler<CreateContactCommand>, CreateContactHandler>(); container.RegisterDecorator(typeof (ICommandHandler<>), typeof (CommandAuditingHandler<>)); container.Register<UnitOfWork>(); }
static void Main(string[] args) { var container = new Container(); container.Register<ISomethingHandler, SimpleSomethingHandler>(); container.RegisterDecorator( typeof(ISomethingHandler), typeof(DoSomethingHandler), ctx => ShouldDecorate(ctx.ServiceType)); container.Verify(); container.GetInstance<ISomethingHandler>().Handle(); }
public static void ConfigureMediator(Container container) { container.Register<IMediator>(() => new Mediator(container.GetInstance<Resolver>())); container.Register(() => Console.Out); container.Register<Resolver>(() => t => container.GetInstance(t)); container.RegisterDecorator( typeof (CommandHandler<,>), typeof (ValidatorHandlerDecorator<,>)); container.RegisterDecorator( typeof(CommandHandler<,>), typeof(TransactionHandlerDecorator<,>), c => c.ImplementationType.Namespace.Contains("Commands") ); container.RegisterDecorator( typeof (CommandHandler<,>), typeof (AuditTrailHandlerDecorator<,>), d => d.ImplementationType.GetInterfaces().Contains(typeof(Auditable)) ); }
public static Container Compose() { var container = new Container(); // TODO: manual registration (one by one) not recommended container.Register<CustomerRepository, InMemoryCustomerRepository>(); container.Register<Transactional, FakeTransactional>(); container.Register(typeof(CommandHandler<>), new[] { typeof(CommandHandler<>).Assembly }); container.RegisterDecorator(typeof(CommandHandler<>), typeof(TransactionalCommandHandler<>)); return container; }
public static Container RegisterCqrsGrpcClients(this Container container, IEnumerable <GrpcCqrsClientConfiguration> configurations) { // cqrs grpc container.Register <IGrpcQueryProcessor, GrpcClientQueryProcessor>(); container.Register <IGrpcCommandDispatcher, GrpcClientCommandDispatcher>(); // cqrs decorators (route requests to grpc or locally) container.RegisterDecorator(typeof(ICommandDispatcher), typeof(CommandDispatcherRouteDecorator), Lifestyle.Transient); container.RegisterDecorator(typeof(IQueryProcessor), typeof(QueryProcessorRouteDecorator), Lifestyle.Transient); // client container.Collection.Register <GrpcCqrsClient>(configurations.Select(x => Lifestyle.Singleton.CreateRegistration( () => { var clientAspect = container.TryGetInstance(typeof(IGrpcClientAspect)) as IGrpcClientAspect; var logger = container.TryGetInstance(typeof(ILogger <GrpcCqrsClient>)) as ILogger <GrpcCqrsClient>; return(new GrpcCqrsClient(x, logger, clientAspect)); }, container )).ToArray()); container.Register <IGrpcClientManager, GrpcClientManager>(); return(container); }
static void Main(string[] args) { Container container = new Container(); container.Register<ILogger, NerdAmigo.Abstractions.Default.DefaultLogger>(Lifestyle.Singleton); container.Register<IPathMapper, CliPathMapper>(Lifestyle.Singleton); container.Register(typeof(IConfigurationProvider<>), typeof(NerdAmigo.Common.Configuration.ConfigurationProvider<>), Lifestyle.Singleton); container.Register<IQueueIdentifierProvider, QueueIdentifierProvider>(Lifestyle.Singleton); container.Register(typeof(IQueueClient<>), typeof(SQSClient<>), Lifestyle.Singleton); container.Register(typeof(IQueueMessageWorker<>), new[] { System.Reflection.Assembly.GetExecutingAssembly() }); container.Register(typeof(QueueMessageProcessor<>), new[] { System.Reflection.Assembly.GetExecutingAssembly() }); container.RegisterDecorator(typeof(IQueueClient<>), typeof(QueueClientLogDecorator<>)); container.Verify(); IQueueClient<SampleMessage> queueClient = container.GetInstance<IQueueClient<SampleMessage>>(); using (CancellationTokenSource cts = new CancellationTokenSource()) { Task sender = Task.Factory.StartNew(() => { int idx = 0; Random r = new Random(); while (!cts.Token.IsCancellationRequested) { queueClient.Enqueue(new SampleMessage() { Name = DateTime.Now.ToShortTimeString(), Id = ++idx }, cts.Token); cts.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(r.Next(60))); } }, cts.Token); QueueMessageProcessor<SampleMessage> messageProcessor = container.GetInstance<QueueMessageProcessor<SampleMessage>>(); messageProcessor.QueueMessageWorkerActivator = new SimpleInjectorQueueMessageWorkerActivator(container); messageProcessor.Begin(cts.Token); Console.ReadKey(); cts.Cancel(); try { sender.Wait(); } catch (AggregateException ex) { foreach (Exception iEx in ex.InnerExceptions) { Console.WriteLine("Task Exception: " + iEx.Message); } } } }
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<>) ); }
public static void Bootstrap() { container = new Container(); BusinessLayerBootstrapper.Bootstrap(container); container.RegisterDecorator(typeof(ICommandHandler<>), typeof(ToWcfFaultTranslatorCommandHandlerDecorator<>)); container.RegisterWcfServices(Assembly.GetExecutingAssembly()); RegisterWcfSpecificDependencies(); container.Verify(); }
/// <summary> /// Application-specific registrations for Simple Injector /// </summary> private static void PerformRegistrations(Container container) { container.Register<ICustomLogger, ConsoleLogger>(Lifestyle.Scoped); container.Register<ICompanyLoader>(() => { if (CurrentConfiguration.LoadFromJson) { return new JsonCompanyLoader(container.GetInstance<ICustomLogger>()); } else { return new HardCodedCompanyLoader(container.GetInstance<ICustomLogger>()); } }); container.RegisterDecorator(typeof (ICompanyLoader), typeof (CompanyLoaderLoggingDecorator)); }
/// <summary> /// Initializes the container. /// </summary> /// <param name="container">The container.</param> private static void InitializeContainer(Container container) { container.RegisterPerWebRequest<IRepository, DatabaseContext>(); container.RegisterSingle<IMessageService, EmailMessageService>(); container.Register<ICommandHandler<DeleteCommand<BlogEntryComment>>, DeleteCommandHandler<BlogEntryComment>>(); container.Register<ICommandHandler<UpdateCommand<BlogEntry>>, UpdateCommandHandler<BlogEntry>>(); container.Register<ICommandHandler<UpdateCommand<BlogEntryFile>>, UpdateCommandHandler<BlogEntryFile>>(); container.RegisterManyForOpenGeneric( typeof(ICommandHandler<>), typeof(ICommandHandler<>).Assembly); container.RegisterDecorator( typeof(ICommandHandler<>), typeof(CommandLoggingDecorator<>)); }
// 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); } } }
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)); }
static void Main() { var container = new Container(); container.Register<IUserRepository, InMemoryUserRepository>(); container.Register<ILogger, ConsoleLogger>(); container.RegisterManyForOpenGeneric(typeof(IHandle<>), AppDomain.CurrentDomain.GetAssemblies()); container.RegisterDecorator(typeof(IHandle<>), typeof(LoggingDecorator<>)); var simpleInjectorServiceLocatorAdapter = new SimpleInjectorServiceLocatorAdapter(container); AppDispatcher.Initialize(app => { // Decorating the pipline AND using IoC: you will see // the action pipleine below wraps any IoC decorators app.GlobalPipeline(pipeline => pipeline.Decorate(handler => { Console.WriteLine("before a"); handler(); Console.WriteLine("after a"); }).Decorate(handler => { Console.WriteLine("before b"); handler(); Console.WriteLine("after b"); }), true); app.UseCommonServiceLocator(simpleInjectorServiceLocatorAdapter); }); var request = new CreateUser { Name = "Jane Smith" }; AppDispatcher.Handle(request); Console.ReadLine(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var container = new SimpleInjector.Container(); container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); container.Register <ICacheService, CacheService>(Lifestyle.Singleton); container.Register <IOrderService, OrderService>(Lifestyle.Scoped); container.RegisterDecorator(typeof(IOrderService), typeof(OrderCacheService)); container.RegisterWebApiControllers(GlobalConfiguration.Configuration); container.Verify(); GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjector.Integration.WebApi.SimpleInjectorWebApiDependencyResolver(container); }
public static void Bind(Container container) { //inject IPrincipal // container.Register(() => // { // if (HttpContext.Current == null || HttpContext.Current.User == null) // return (null as IPrincipal); // // return HttpContext.Current.User; // }); //refer to assemblies containing handlers container.RegisterManyForOpenGeneric(typeof (IQueryHandler<,>), new[] { typeof (CreateContactCommand).Assembly }); container.RegisterManyForOpenGeneric(typeof (ICommandHandler<>), new[] { typeof (CreateContactCommand).Assembly }); //register repository implementations (you would do this by convention normally) container.RegisterWebApiRequest<ICreateAContact, ContactCreator>(); container.RegisterWebApiRequest<IReadOnlyRepository>(() => { //you may wish to get this from the container, but it could be in scope with a consumer that writes var context = new ContactAppEntities(); context.Configuration.AutoDetectChangesEnabled = false; return new ReadOnlyRepository(context); }); container.RegisterWebApiRequest<ContactAppEntities>(); container.RegisterWebApiRequest<EfUnitOfWork>(); container.Register<DbContext>(container.GetInstance<ContactAppEntities>); container.Register<IUnitOfWork>(container.GetInstance<EfUnitOfWork>); container.RegisterDecorator(typeof (ICommandHandler<>), typeof (EfUnitOfWorkTransactionCommandHandlerDecorator<>)); container.RegisterDecorator(typeof (ICommandHandler<>), typeof (PostCommitCommandHandlerDecorator<>)); container.RegisterWebApiRequest<PostCommitRegistrar>(); container.Register<IPostCommitRegistrar>(container.GetInstance<PostCommitRegistrar>); //TODO auditing should log via a bus or separate asynchronous repository, not to a logger bool traceEnabled; bool.TryParse(ConfigurationManager.AppSettings["Audit:Enabled"], out traceEnabled); if (traceEnabled) { container.RegisterDecorator(typeof (ICommandHandler<>), typeof (CommandAuditor<>)); container.RegisterDecorator(typeof (IQueryHandler<,>), typeof (QueryAuditor<,>)); } //TODO no need, this is config based // else // { // container.RegisterSingle<ILog, NullLogger>(); // } container.RegisterDecorator(typeof (IQueryHandler<,>), typeof (CacheablePerUserQueryHandler<,>)); container.RegisterDecorator(typeof (ICommandHandler<>), typeof (CommandValidator<>)); container.RegisterDecorator(typeof (IQueryHandler<,>), typeof (QueryValidator<,>)); container.RegisterWebApiRequest<IMediator, WebApiMediator>(); /* we are using data annotations for validation, so we must inform simple injector * to use this container when IServiceProvider is requested for validation */ container.RegisterWebApiRequest<IServiceProvider>(() => container); }
public RegisterDecoratorPredicate() { var container = new Container(); container.RegisterDecorator(typeof(ICommon), typeof(CommonImpl1), context => true); }
public static Container AddQueriesValidation(this Container container) { container.RegisterDecorator(typeof(IAsyncQueryHandler <,>), typeof(ValidateAsyncQueryDecorator <,>), Lifestyle.Transient); container.RegisterDecorator(typeof(IQueryHandler <,>), typeof(ValidateQueryDecorator <,>), Lifestyle.Transient); 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; }
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); }
private static void RegisterTypes(Container container) { #region Configuration container.RegisterSingleton<IConfigurationProvider, AppSettingsConfigurationProvider>(); container.RegisterSingleton<IConverter<DynamicTableEntity, AwsOptions>, DynamicAwsOptionsConverter>(); container.RegisterSingleton<IOptionsProvider<AwsOptions[]>, AzureAwsOptionsProvider>(); container.RegisterDecorator<IOptionsProvider<AwsOptions[]>, LazyOptionsProviderAdapter<AwsOptions[]>>(Lifestyle.Singleton); container.RegisterFactory<AwsOptions, RoundrobinAwsOptionsFactory>(Lifestyle.Singleton); #endregion #region Providers container.RegisterSingleton<IDateTimeProvider, UtcDateTimeProvider>(); #endregion #region Scheduler container.RegisterFactory<TaskSchedulerSettings, TaskSchedulerSettingsFactory>(Lifestyle.Singleton); container.RegisterFactory<ITaskScheduler, TaskSchedulerSettings, DelayTaskSchedulerFactory>(Lifestyle.Singleton); container.RegisterSingleton<IScheduler>(Scheduler.Default); container.RegisterSingleton<ITaskScheduler, DelayTaskScheduler>(); #endregion #region Http container.Register<HttpClient>(() => HttpClientFactory.Create()); container.Register<IHttpClient, HttpClientAdapter>(); #endregion #region Azure container.RegisterFactory<AzureOptions, AzureOptionsFactory>(Lifestyle.Singleton); container.Register<IAzureContainerClient, AzureContainerClient>(); container.Register<IBlobClient, AzureBlobClient>(); container.Register<ITableClient, AzureTableClient>(); container.Register<IQueueClient, AzureQueueClient>(); container.Register<IAzureClient, AzureClient>(); container.Register<IConverter<Category, string>, JsonCategoryConverter>(); container.Register<IConverter<string, Product>, JsonProductConverter>(); container.Register<IAzureCategoryProvider, AzureCategoryProvider>(); #endregion #region Amazon container.Register<ITagGenerator, RandomTagGenerator>(); container.Register<IArgumentBuilder, AwsArgumentBuilder>(); container.Register<IPipeline<string>, PercentUrlEncodingPipeline>(); container.Register<IUrlEncoder, PercentUrlEncoder>(); container.Register<IQueryBuilder, EncodedQueryBuilder>(); container.RegisterFactory<System.Security.Cryptography.HashAlgorithm, AwsAlgorithmFactory>(); container.Register<IQuerySigner, AwsQuerySigner>(); container.Register<IUrlBuilder, AwsUrlBuilder>(); container.RegisterFactory<IItemResponse, string, XmlItemResponseFactory>(); container.Register<IPipeline<Product, XElement, SearchCriteria>, ResponseGroupProductPipeline>(Lifestyle.Singleton); container.RegisterFactory<Product, XElement, SearchCriteria, XmlProductFactory>(); container.Register<IFilter<XElement>, PrimaryVariantlItemFilter>(); container.Register<IAwsClient, XmlAwsClient>(); container.Register<IAwsProductProvider, AwsProductProvider>(); #endregion }
// TODO: Use Assembly Discovery.. void SetupContainer(Func<ISteamApi> steamApi) { _assemblies = new[] {Assembly.GetExecutingAssembly()}; _container = new Container(); _container.Options.DefaultScopedLifestyle = new ExecutionContextScopeLifestyle(); _container.RegisterSingleton<ICheatImpl, CheatImpl>(); _container.RegisterSingleton<IExceptionHandler, UnhandledExceptionHandler>(); _container.RegisterSingleton<IActionDispatcher>( () => new ActionDispatcher(_container.GetInstance<IMediator>(), null)); BootstrapperBridge.RegisterMessageBus(_container); _container.RegisterSingleton<IMessageBusProxy, MessageBusProxy>(); _container.RegisterSingleton<ISteamHelper>(SteamHelper.Create()); _container.RegisterPlugins<IHandleExceptionPlugin>(_assemblies, Lifestyle.Singleton); _container.RegisterSingleton<SteamSession.SteamSessionFactory>(); _container.RegisterSingleton<ISteamSessionFactory>(_container.GetInstance<SteamSession.SteamSessionFactory>); _container.RegisterSingleton<ISteamSessionLocator>(_container.GetInstance<SteamSession.SteamSessionFactory>); _container.RegisterSingleton<IServiceMessenger, ServiceMessenger>(); _container.RegisterSingleton<ISteamDownloader, SteamDownloader>(); _container.RegisterSingleton<Api.Services.ISteamApi, SteamApi>(); _container.RegisterSingleton(steamApi); _container.RegisterSingleton<IEventStorage, EventStorage>(); _container.RegisterSingleton<ISafeCallFactory, SafeCallFactory>(); _container.RegisterValidation(_assemblies); _container.RegisterMediator(_assemblies); _container.RegisterDecorator<IMediator, MediatorLoggingDecorator>(); _container.Register<IRequestScope, RequestScope>(Lifestyle.Scoped); _container.RegisterSingleton<IRequestScopeLocator, RequestScopeService>(); }
public RegisterDecoratorNonGeneric() { var container = new Container(); container.RegisterDecorator(typeof(ICommon), typeof(CommonImpl1)); }