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<,>));
        }
Ejemplo n.º 2
0
        private void SetupIoc()
        {
            container = new Container();
            container.Register<ICommandHandlerDisptcher, CommandHandlerDisptcher>();
            container.Register<IQueryHandlerDispatcher, QueryHandlerDispatcher>();

            container.RegisterManyForOpenGeneric(typeof(IQueryHandlerAsync<,>), typeof(GetQuestionnaireQueryHandler).Assembly);
            container.RegisterManyForOpenGeneric(typeof(ICommandHandlerAsync<,>), typeof(CreateAnswersCommandHandler).Assembly);

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

            container.Verify();

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
        }
Ejemplo n.º 3
0
 public void Execute_InvokesQueryHandler_UsingContainerForResolution()
 {
     var container = new Container();
     container.RegisterSingle<IProcessQueries, QueryProcessor>();
     container.RegisterManyForOpenGeneric(typeof(IHandleQuery<,>), Assembly.GetExecutingAssembly());
     container.Verify();
     var queries = container.GetInstance<IProcessQueries>();
     var result = queries.Execute(new FakeQueryWithoutValidator());
     result.ShouldEqual("faked");
 }
        public SimpleInjectorTests()
        {
            var container = new Container();

            container.Register<A, AImpl>();
            container.RegisterManyForOpenGeneric(typeof(B<>), typeof(A).Assembly);
            container.RegisterManyForOpenGeneric(typeof(C<,>), ((t, impls) =>
            {
                foreach (var impl in impls.Where(impl => !impl.IsAbstract))
                {
                    container.Register(impl);
                }
            }), typeof(A).Assembly);
            container.RegisterManyForOpenGeneric(typeof(D<>), typeof(A).Assembly);
            container.RegisterManyForOpenGeneric(typeof(E<,>), typeof(A).Assembly);
            container.RegisterManyForOpenGeneric(typeof(F<,>), typeof(A).Assembly);
            AllowToResolveVariantCollections(container);

            ServiceLocator = new SimpleInjectorServiceLocatorAdapter(container);
        }
Ejemplo n.º 5
0
 public void ValidateQuery_InvokesValidator_UsingContainerForResolution()
 {
     var container = new Container();
     container.RegisterSingle<IProcessValidation, ValidationProcessor>();
     container.RegisterManyForOpenGeneric(typeof(IValidator<>), Assembly.GetExecutingAssembly());
     container.Verify();
     var validation = container.GetInstance<IProcessValidation>();
     var result = validation.Validate(new FakeQueryWithValidator { InputValue = null });
     result.IsValid.ShouldBeFalse();
     result.Errors.Count.ShouldEqual(1);
 }
Ejemplo n.º 6
0
        public void Execute_InvokesCommandHandler_UsingContainerForResolution()
        {
            var container = new Container();
            container.RegisterSingle<IProcessCommands, CommandProcessor>();
            container.RegisterManyForOpenGeneric(typeof(IHandleCommand<>), Assembly.GetExecutingAssembly());
            container.Verify();
            var commands = container.GetInstance<IProcessCommands>();
            var command = new FakeCommandWithoutValidator();

            commands.Execute(command);

            command.ReturnValue.ShouldEqual("faked");
        }
        public static void Register(HttpConfiguration config)
        {
            var container = new Container();
            var webapiLifestyle = new WebApiRequestLifestyle();
            container.RegisterWebApiRequest<ITransactionEngine, TransactionEngine>();

            BuildManager.GetReferencedAssemblies();
            AppDomain currentDomain = AppDomain.CurrentDomain;

            container.RegisterManyForOpenGeneric(typeof(IQueryHandler<,>), webapiLifestyle, currentDomain.GetAssemblies());
            container.RegisterManyForOpenGeneric(typeof(ICommandHandler<>), webapiLifestyle, currentDomain.GetAssemblies());

            // Veroorzaakt een StackOverFlowException bij opvragen:
            container.RegisterOpenGeneric(typeof(ICommandHandler<>), typeof(UpdateFeaturesCommandHandler<,>), webapiLifestyle,
                c => !c.Handled);

            container.RegisterSingle<ITransactionalCommandHandlerFactory>(new TransactionalCommandHandlerFactory(container));

            container.RegisterWebApiControllers(config);
            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
        }
Ejemplo n.º 8
0
        /// <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 static void InitializeContainer(Container container)
        {
            // Pre-requisites:
            container.RegisterSingle<ILogger, EmptyLogger>();
            container.RegisterSingle<ITextKeyFactory, DefaultTextKeyFactory>();
            container.RegisterSingle<ITypeNameFactory, DefaultTypeNameFactory>();

            // Xml file repository:
            var translationsPath = HttpContext.Current.Server.MapPath("~/App_Data/translations.xml");
            container.RegisterSingle<ILocalizedRepository>(() => new XmlFileRepository(translationsPath));

            var fallbackCulture = CultureInfo.GetCultureInfo("en-US");

            // View localization:
            container.RegisterSingle<IViewNameFactory, DefaultViewNameFactory>();
            container.RegisterSingle<ILocalizedStringProvider>(
                () =>
                new DefaultLocalizedStringProvider(
                    // provider used for views and legacy classes localization
                    container.GetInstance<ILocalizedRepository>(),
                    container.GetInstance<ITextKeyFactory>(),
                    container.GetInstance<ILogger>(),
                    CultureInfo.GetCultureInfo("fr-FR"), // native text is in french...
                    fallbackCulture,
                    DefaultMissingLocalizedStringExtensionPoint.Instance
                    ));

            // Legacy class localization:
            container.RegisterManyForOpenGeneric(typeof(StringProvider<>), typeof(StringProvider<>).Assembly);

            // Model metadata localization:
            container.RegisterSingle<Localization.MvcProviders.ModelMetadataProvider>(() => new Localization.MvcProviders.ModelMetadataProvider(
                                                                           new DefaultLocalizedStringProvider(
                                                                               container.GetInstance<ILocalizedRepository>(),
                                                                               container.GetInstance<ITextKeyFactory>(),
                                                                               container.GetInstance<ILogger>(),
                                                                               CultureInfo.GetCultureInfo("en-US"), // Names of model properties are in english...
                                                                               fallbackCulture,
                                                                               DefaultMissingLocalizedStringExtensionPoint.Instance),
                                                                            container.GetInstance<ITypeNameFactory>(),
                                                                            container.GetInstance<ILogger>()));
        }
        /// <summary>Initialize the container and register it as MVC3 Dependency Resolver.</summary>
        public static void Initialize()
        {
            // Did you know the container can diagnose your configuration? Go to: https://bit.ly/YE8OJj.
            var container = new Container();
            
            InitializeContainer(container);

            // Register controllers
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

            // Register validators
            container.RegisterManyForOpenGeneric(typeof(IValidator<>), typeof(OrderValidator).Assembly);

            // Verify registrations
            container.Verify();

            // Set validator factory
            FluentValidationModelValidatorProvider.Configure(GlobalConfiguration.Configuration,
                provider => provider.ValidatorFactory = new FluentValidatorFactory(container));

            // Set dependency resolver
            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);
        }
Ejemplo n.º 11
0
        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();
        }
Ejemplo n.º 12
0
        public static Container Build()
        {
            var container = new Container();
            container.RegisterPerWebRequest<IDbContext>(() => new AppDbContext("AppDb"));
            container.RegisterPerWebRequest<ICurrentUser,FormsAuthenticationCurrentUser>();
            container.RegisterSingle<ICacheProvider,AppCacheProvider>();
            container.Register<ILogger,NLogLogger>();

            container.RegisterManyForOpenGeneric(typeof(IGridModelBuilder<,>), typeof(IGridModelBuilder<,>).Assembly);
            container.RegisterManyForOpenGeneric(typeof(IModelBuilder<>), typeof(IModelBuilder<>).Assembly);
            container.RegisterManyForOpenGeneric(typeof(IModelBuilder<,>), typeof(IModelBuilder<,>).Assembly);
            container.RegisterManyForOpenGeneric(typeof(IModelHandler<>), typeof(IModelHandler<>).Assembly);
            container.RegisterManyForOpenGeneric(typeof(IModelHandler<,>), typeof(IModelHandler<,>).Assembly);
            container.RegisterManyForOpenGeneric(typeof(IFileModelBuilder<>), typeof(IFileModelBuilder<>).Assembly);
            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
            container.RegisterMvcIntegratedFilterProvider();

            container.Verify();
            return container;
        }
Ejemplo n.º 13
0
 public void RegisterServices(Container container)
 {
     container.RegisterManyForOpenGeneric(typeof(IActionFilter<>), container.RegisterAll, typeof(IActionFilter<>).Assembly);
 }
Ejemplo n.º 14
0
 private static void InitializeContainer(Container container)
 {
     container.RegisterSingle<IServiceProvider>(container);
     container.RegisterManyForOpenGeneric(typeof(IValidator<>), Assembly.GetExecutingAssembly());
 }
Ejemplo n.º 15
0
        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);
        }
Ejemplo n.º 16
0
        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;
        }