コード例 #1
1
        static void Main(string[] args)
        {
            //create the IOC container
            var container = new Container();
            //bind all our types to the interfaces
            container.Register<IContactCreator, ContactCreator>();
            container.Register<IContactLister, ContactLister>();
            container.Register<IContactStore, MemoryContactStore>();
            container.Register<ILog, NoLogging>();
            
            var creator = container.GetInstance<IContactCreator>();
            creator.Create(new Contact()
                {
                    Name = "Guy"
                });
            creator.Create(new Contact()
            {
                Name = "Ascension"
            });
            creator.Create(new Contact()
            {
                Name = "Richard"
            });

            var lister = container.GetInstance<IContactLister>();

            var contacts = lister.GetList();
            foreach (var contact in contacts)
            {
                Console.WriteLine(contact.Name);
            }
            Console.ReadKey();
        }
コード例 #2
0
ファイル: frm_Main.cs プロジェクト: miladsoft/Sample_Sqlite
 private static void Bootstrap()
 {
     container = new SimpleInjector.Container();
     container.Register <IUsersService, UserServices>();
     container.Register <Iunitofwork, SampleContext>();
     container.Register <frm_AddEdit>();
 }
コード例 #3
0
ファイル: Program.cs プロジェクト: NahumLitvin/Ioc.QuickStart
        static void Main(string[] args)
        {
            // 1. Create a new Simple Injector container
            var container = new Container();

            // 2. Configure the container (register)
            container.Register<IMongoProvider, MongoProvider>(Lifestyle.Singleton);
            container.Register<IInputProvider, MongoInputProvider>();
            container.Register<IOutputProvider, MongoOutputProvider>();
            container.Register<IParseProvider,ConsoleParseProvider>();
            container.Register<IMathProvider, DefaultMathProviderProvider>();

            // 3. Optionally verify the container's configuration.
            container.Verify();

            /*
            var calc = new Calculator(
                new MongoInputProvider(new MongoProvider("localhost:\\mongo")), //<===
                new MongoOutputProvider(new MongoProvider("localhost:\\mongo")),//<=== 
                new ConsoleParseProvider(),
                new DefaultMathProviderProvider()
                );

            */
            var calc = container.GetInstance<Calculator>();
            calc.MainLoop();

            Console.ReadLine();
        }
コード例 #4
0
        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name="container">容器</param>
        /// <param name="containerWrapper">容器封装类</param>
        public static void RegisterService(Container container, IContainer containerWrapper)
        {
            //注册产品服务类
            container.Register<IProductService>(() =>
            {
                var productService = new ProductService();
                productService.Initialize(containerWrapper, ApplicationMediator.ProductDbSessionCached);
                return productService;
            });

            //注册订单服务类
            container.Register<IOrderService>(() =>
            {
                var orderService = new OrderService();
                orderService.Initialize(containerWrapper, ApplicationMediator.ProductDbSessionCached);
                return orderService;
            });

            //注册功能菜单服务类
            container.Register<IFunctionMenuService>(() =>
            {
                var functionService = new FunctionMenuService();
                functionService.Initialize(containerWrapper, ApplicationMediator.ProductDbSessionCached);
                return functionService;

            });
        }
コード例 #5
0
        public void RegisterServices(Container container)
        {
            //Config
            container.RegisterWebApiRequest<IDbSettings>(() => new DbSettings(Constants.ConnectionName));

            //DbContext
            container.RegisterWebApiRequest<IPropertyMatrixContext>(() => new PropertyMatrixContext(container.GetInstance<IDbSettings>()));

            //Services
            container.Register<IPriceRangeService, PriceRangeService>();
            container.Register<IQuoteService, QuoteService>();
            container.Register<IAppointmentService, AppointmentService>();
            container.Register<ISearchService, SearchService>();

            //Data
            container.Register<IPriceRangeRepository, PriceRangeRepository>();
            container.Register<IQuoteRepository, QuoteRepository>();
            container.Register<IAppointmentRepository, AppointmentRepository>();
            container.Register<ISearchRepository, SearchRepository>();

            //Mapping
            container.Register<IMapToExisting<PriceRange, PriceRange>, PriceRangeMapper>();

            //Reference Generator
            container.Register<IReferenceGenerator, CryptographicReferenceGenerator>();

            container.Verify();
        }
コード例 #6
0
ファイル: QueryPackage.cs プロジェクト: hartmanns/ScaffoldR
        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
                );
        }
コード例 #7
0
        static void Main(string[] args)
        {
            Console.WriteLine("DEMO >> DbSet");

            var contenedor = new SimpleInjector.Container();

            contenedor.Register <IConeccion, Coneccion>(Lifestyle.Singleton);
            contenedor.Register <Productos>(Lifestyle.Singleton);

            var productos = contenedor.GetInstance <Productos>();

            var a = productos.Crear();

            a.Descripcion = "Coca cola";
            a.Precio      = 90;

            productos.Agregar(a);
            Pausa();

            a.PonerOferta();
            productos.Actualizar(a);
            Pausa();

            productos.Borrar(a);
            Pausa();

            var ps = productos.Traer("Precio < 90");
        }
コード例 #8
0
        public void RegisterDependencies(Container container)
        {
            container.Register <ITaskRepository, TaskRepository>();
            container.Register <NewLeadService, NewLeadService>();

            container.Verify();
        }
コード例 #9
0
        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;
        }
コード例 #10
0
        public void RegisterServices(Container container, CompositionRootSettings settings)
        {
            if (settings.ViewModelAssemblies == null) return;

            container.RegisterSingleton<IProcessViewModels, ViewModelProcessor>();

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

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

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

            container.RegisterDecorator(
                 typeof(IHandleViewModel<,>),
                 typeof(ViewModelWithArgumentNotNullDecorator<,>),
                Lifestyle.Singleton
            );
        }
コード例 #11
0
ファイル: DependencyConfig.cs プロジェクト: aduggleby/dragon
        public static void Register(Container container)
        {
            container.RegisterOpenGeneric(typeof(IRepository<>), typeof(Repository<>));

            // Single services
            container.Register<IContext, DefaultContext>();
            container.Register<ICommandPersister, DefaultCommandPersister>();
            container.Register<ICommandSerializer, NewtonsoftCommandSerializer>();
            //container.Register<ICommandSerializer, JilCommandSerializer>();

            AddInterfaceForEachDerivedType(container, typeof(TableBase), typeof(ITableBeforeSave<>));
            AddInterfaceForEachDerivedType(container, typeof(TableBase), typeof(ITableAfterSave<>));

            AddInterfaceForEachDerivedType(container, typeof(CommandBase), typeof(ICommandBeforeProcess<>));
            AddInterfaceForEachDerivedType(container, typeof(CommandBase), typeof(ICommandBeforeSave<>));
            AddInterfaceForEachDerivedType(container, typeof(CommandBase), typeof(ICommandAfterSave<>));

            // default persister
            container.RegisterOpenGeneric(typeof(ICommandSave<>), typeof(DefaultSaver<>));

            // override persisters
            container.Options.AllowOverridingRegistrations = true;

            //container.RegisterOpenGeneric(typeof(InsertCommandFor<>), typeof(SimpleCommandsDefaultSaver<>));
            //container.RegisterManyForOpenGeneric(typeof(ICommandSave<>), AppDomain.CurrentDomain.GetAssemblies());
            //container.RegisterManyForOpenGeneric(typeof(ICommandSave<>).MakeGenericType(typeof(InsertCommandFor<>)), AppDomain.CurrentDomain.GetAssemblies());
            /*
            ReplaceInterfaceForEachDerivedType(container, 
                typeof(SimpleCommand<>), 
                typeof(ICommandSave<>).MakeGenericType(typeof(InsertCommandFor<>))
                );*/

            //RegisterAllPersisters();

        }
コード例 #12
0
        protected void Application_Start()
        {
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

            // Register your types, for instance using the scoped lifestyle:
            container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Scoped);
            container.Register<IUserManager, UserManager>();
            container.Register<IOrderManagerEx, OrderManagerEx>();

            // This is an extension method from the integration package.
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);
            AutoMapperConfig.Configure();
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
        }
コード例 #13
0
 private static void RegisterDependencies(Container container)
 {
     container.Register<PlayerService, PlayerService>(Lifestyle.Scoped);
     container.Register<ConfigService, ConfigService>(Lifestyle.Scoped);
     container.Register<ClubService, ClubService>(Lifestyle.Scoped);
     container.Register<TeamService, TeamService>(Lifestyle.Scoped);
 }
コード例 #14
0
        private static void ConfigureAspNetIdentity(Container container)
        {
            container.Register(
                typeof(IUserStore<Administrator>),
                () =>
                {
                    var session = container.GetInstance<IAsyncDocumentSession>();
                    session.Advanced.UseOptimisticConcurrency = true;
                    return new RavenUserStore<Administrator, RavenRole>(session);
                },
                Lifestyle.Scoped);

            container.Register(
                typeof(UserManager<Administrator>),
                () =>
                {
                    var manager = new UserManager<Administrator>(container.GetInstance<IUserStore<Administrator>>());
                    manager.UserValidator = new UserValidator<Administrator>(manager)
                    {
                        AllowOnlyAlphanumericUserNames = false,
                    };
                    return manager;
                },
                Lifestyle.Scoped);
        }
コード例 #15
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var ambientDbLocater = new AmbientDbContextLocator();

            var container = new Container();
            container.Options.DefaultScopedLifestyle = new LifetimeScopeLifestyle();

            container.Register<IAmbientDbContextLocator, AmbientDbContextLocator>(Lifestyle.Singleton);
            container.Register<IUnitOfWork>(() => new EFUnitOfWork(), Lifestyle.Scoped);

            container.Register<IUnitOfWorkFactory>(
                () => new EFUnitOfWorkFactory(System.Data.IsolationLevel.ReadUncommitted));

            container.Register<IClienteRepository, ClienteRepository>();
            container.Register<IClientesService, ClientesService>();

            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
            container.RegisterMvcIntegratedFilterProvider();

            container.Verify();

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: Boggin/Consolas
        public override void Configure(Container container)
        {
            container.Register<IConsole, SystemConsole>();
            container.Register<IThreadService, ThreadService>();

            ViewEngines.Add<RazorViewEngine>();
        }
コード例 #17
0
        /// <summary>Initialize the container and register it as MVC3 Dependency Resolver.</summary>
        public static void Initialize()
        {
            //var container = new Container();
            //container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

            //InitializeContainer(container);

            //container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

            //container.Verify();

            //DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

            // 1. Create a new Simple Injector container
            var container = new Container();

            // 2. Configure the container (register)
            container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Transient);

            container.Register<SampleIOC.Logging.ILogging, MailLogger>(Lifestyle.Singleton);

            // 3. Optionally verify the container's configuration.
            container.Verify();

            // 4. Register the container as MVC3 IDependencyResolver.
            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
コード例 #18
0
 private static void SetupDataContext(Container container)
 {
     container.Register<ILibraryContext, LibraryContext>(Lifestyle.Singleton);
     container.Register<IBookRepository, BookRepository>(Lifestyle.Scoped);
     container.Register<IAuthorRepository, AuthorRepository>(Lifestyle.Scoped);
     container.Register<IBookAuthorRepository, BookAuthorRepository>(Lifestyle.Scoped);
 }
コード例 #19
0
 private static void InitializeContainer(Container container)
 {
     container.Register<IConfigurationProvider, AppSettingsConfigurationProvider>();
     container.Register<IMetadataProvider, TwitterSecurityTokenServiceConfiguration>();
     container.Register<SecurityTokenServiceConfiguration, TwitterSecurityTokenServiceConfiguration>();
     container.Register<IIdentityProvider, TwitterSecurityTokenService>();
 }
コード例 #20
0
ファイル: Global.asax.cs プロジェクト: jsnmgpnty/Blogness2.0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

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

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

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

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

            DependencyResolver.SetResolver(new SimpleInjector.Integration.Web.Mvc.SimpleInjectorDependencyResolver(container));
        }
コード例 #21
0
ファイル: Registry.cs プロジェクト: rg-kristianwilson/People
 public void RegisterServices(Container container)
 {
     container.RegisterWebApiRequest<IDbFactory>(() => new DbFactory(ConfigurationManager.ConnectionStrings["People"].ConnectionString));
     container.Register<IPeopleRepository, PeopleRepository>();
     container.Register<IPeopleService, PeopleService>();
     container.Verify();
 }
コード例 #22
0
ファイル: BootStrapper.cs プロジェクト: varcalsys/ImovelBens
 public static void RegisterServices(Container container)
 {
     container.Register<ApplicationDbContext>(Lifestyle.Scoped);
     container.RegisterPerWebRequest<IUserStore<ApplicationUser>>(() => new UserStore<ApplicationUser>(new ApplicationDbContext()));
     container.Register<ApplicationUserManager>(Lifestyle.Scoped);
     container.Register<ApplicationSignInManager>(Lifestyle.Scoped);
 }
コード例 #23
0
 public static void Initialize(Container container, Lifestyle lifestyle)
 {
     container.Register<IProdutoRepository, ProdutoRepository>(lifestyle);
     container.Register<ICompraRepository, CompraRepository>(lifestyle);
     container.Register<ICompraItemRepository, CompraItemRepository>(lifestyle);
     container.Register<IFornecedorRepository, FornecedorRepository>(lifestyle);
 }
コード例 #24
0
        public static void ConfigContainer(Container container)
        {
            #region - MAPPER -
            var mapperConfig = AutoMapperConfig.GetMapperConfiguration();
            container.RegisterSingleton<IConfigurationProvider>(mapperConfig);
            container.Register(() => mapperConfig.CreateMapper());
            container.Register<IMapperAdapter, AutoMapperAdapter>();
            #endregion

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

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

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

            container.Register<UserManager<Usuario, long>>(Lifestyle.Scoped);
            container.Register<IRefreshTokenDomain, RefreshTokenDomain>(Lifestyle.Scoped);
            container.Register<IClientDomain, ClientDomain>(Lifestyle.Scoped);
            container.Register<IAccountDomain, AccountDomain>(Lifestyle.Scoped);
            #endregion
        }
コード例 #25
0
        /// <summary>
        /// Register services here
        /// </summary>
        /// <param name="container"></param>
        private static void ConfigureContainer(Container container)
        {
            //Register the service
            container.Register<Service>();

            //Register dependencies
            container.Register<IDependency, Dependency>();
        }
コード例 #26
0
 public static void Register(Container container, Lifestyle lifestyle)
 {
     //container.RegisterAll<IConexao<T>>(Conexao<T>)>(lifestyle);
     container.Register<ICompraDal, CompraDal>(lifestyle);
     container.Register<ICompraItemDal, CompraItemDal>(lifestyle);
     container.Register<IClienteDal, ClienteDal>(lifestyle);
     container.Register<IFornecedorDal, FornecedorDal>(lifestyle);
 }
コード例 #27
0
 public static void Config(Container container)
 {
     container.RegisterPerWebRequest<IDatabaseFactory,DatabaseFactory>();
     container.RegisterOpenGeneric(typeof(IRepository<>), typeof(Repository<>));
     container.RegisterPerWebRequest<IUnitOfWork, UnitOfWork>();
     container.Register<IProductRepository, ProductRepository>();
     container.Register(()=>new SrcSamples());
 }
コード例 #28
0
 public void Register(Type concrete, Contracts.Lifestyle lifestyle)
 {
     if (_child)
     {
         return;
     }
     _container.Register(concrete, concrete, ConvertLifestyle(lifestyle));
 }
コード例 #29
0
        public void TestFixtureSetUp()
        {
            _container = new Container();

            //Register services
            _container.Register<TestService>();
            _container.Register<ITestDependency, TestDependency>();
        }
コード例 #30
0
        private static void CriarContainerInjecaoDependencia()
        {
            container = new SimpleInjector.Container();

            container.Register <IClienteRepositorio <Cliente>, ClienteRepositorio>(Lifestyle.Singleton);
            container.Register <IContaCorrenteRepositorio <ContaCorrente>, ContaCorrenteRepositorio>(Lifestyle.Singleton);
            container.Register <IContaEspecialRepositorio <ContaEspecial>, ContaEspecialRepositorio>(Lifestyle.Singleton);
            container.Register <Form1>();
        }
コード例 #31
0
        public void Step4()
        {
            var container = new Container();

            container.Register<IDependency1>(() => new Dependency1());
            container.Register<IService1, Service1a>();

            container.Verify(VerificationOption.VerifyAndDiagnose);
        }
コード例 #32
0
        public void Step5()
        {
            var container = new Container();
            container.Options.ConstructorResolutionBehavior = new MostResolvableConstructorBehavior(container);

            container.Register<IDependency1>(() => new Dependency1());
            container.Register<IService1, Service1a>();
            container.Verify(VerificationOption.VerifyAndDiagnose);
        }
コード例 #33
0
        public void Initialize()
        {
            messageContainer = new SimpleInjector.Container();

            messageContainer.Register <NLog.ILogger, LoggingCommand>(Lifestyle.Singleton);
            messageContainer.Register <IMessageProcessor <UasHeartbeat>, HeartbeatProcessor>(Lifestyle.Singleton);
            messageContainer.Register <IMessageProcessor <UasBatteryStatus>, BatteryStatusProcessor>(Lifestyle.Singleton);
            messageContainer.Register <IMessageProcessor <UasStatustext>, StatustextProcessor>(Lifestyle.Singleton);
        }
コード例 #34
0
		private static void SetupDependencies(Container container)
		{
			container.Register<SiteContext>(new WebRequestLifestyle());

			container.Register<IPostService, PostService>(new WebRequestLifestyle());
			container.Register<IPageService, PageService>(new WebRequestLifestyle());
			container.Register<ISearchService, SearchService>(new WebRequestLifestyle());
			container.Register<IUserService, UserService>(new WebRequestLifestyle());
		}
コード例 #35
0
        private static void InitializeContainer(Container container)
        {


            // For instance:
            // container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);
            container.Register<AmigoBusiness,AmigoBusiness>();
            container.Register<AmigoDAO,AmigoDAO>();
        }
コード例 #36
0
 private static Container InitContanier()
 {
     var container = new Container();
     container.Register<ILogger, ConsoleLogger>();
     container.Register<ICredit, Credit>();
     //container.Register<IInterceptor,PerformanceLoggingInterceptor>();
     container.InterceptWith<PerformanceLoggingInterceptor>(type => type== typeof(ICredit));
     return container;
 }
コード例 #37
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>();
     return(container);
 }
コード例 #38
0
        private static void InitializeContainer(SimpleInjector.Container container)
        {
            container.Options.DefaultScopedLifestyle = new ExecutionContextScopeLifestyle();
            container.Register <ErpContext>(Lifestyle.Scoped);
            container.Register(typeof(IUnitOfWork <>), typeof(UnitOfWork <>), Lifestyle.Scoped);

            container.Register <ISorteioService, SorteioService>();
            container.Register <IJogadorService, JogadorService>();
            container.Register <IJogoService, JogoService>();
        }
コード例 #39
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);
 }
コード例 #40
0
        private void RegisterAllDependenciesForInMemoryDependencyResolver(SimpleInjector.Container container)
        {
            var inMemoryEventRouter   = new InMemoryEventRouter();
            var inMemoryCommandRouter = new InMemoryCommandRouter();

            container.Register <ICommandSubscriber>(() => inMemoryCommandRouter, Lifestyle.Singleton);
            container.Register <ICommandPublisher>(() => inMemoryCommandRouter, Lifestyle.Singleton);
            container.Register <IEventPublisher>(() => inMemoryEventRouter, Lifestyle.Singleton);
            container.Register <IEventSubscriber>(() => inMemoryEventRouter, Lifestyle.Singleton);
            container.Register <IEventStore>(() => new InMemoryEventStore(container.GetInstance <IEventPublisher>()), Lifestyle.Singleton);
        }
コード例 #41
0
        public static void RegisterServices(SimpleInjector.Container container)
        {
            // App
            container.Register <IClientAppService, ClientAppService>(Lifestyle.Scoped);

            // Domain
            container.Register <IClientService, ClientService>(Lifestyle.Scoped);

            // Data
            container.Register <IClientRepository, ClientRepository>(Lifestyle.Scoped);
        }
コード例 #42
0
ファイル: Startup.cs プロジェクト: rosemberg-al/proclin
        private static void InitializeContainer(Container container)
        {
            //container.Register<Security>(Lifestyle.Scoped);
            // container.Register(typeof(IUnitOfWork<>), typeof(UnitOfWork<>), Lifestyle.Scoped);
            container.Options.DefaultScopedLifestyle = new ExecutionContextScopeLifestyle();
            container.Register <ClinicasContext>(Lifestyle.Scoped);
            container.Register(typeof(IUnitOfWork <>), typeof(UnitOfWork <>), new ExecutionContextScopeLifestyle());
            container.RegisterWebApiRequest <IUserService, UserService>();
            container.Register <IPacienteRepository, PacienteRepository>();
            container.Register <IPacienteService, PacienteService>();

            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
        }
コード例 #43
0
        private static void Register()
        {
            // repositories
            _container.Register <IPersonsRepository, PersonsRepository>(Lifestyle.Scoped);
            _container.Register <ICountryRepository, CountryRepository>(Lifestyle.Scoped);
            _container.Register <IAuthTokenRepository, AuthTokenRepository>(Lifestyle.Scoped);

            //services
            _container.Register <IPersonsService, PersonsService>(Lifestyle.Scoped);
            _container.Register <IAuthTokenService, AuthTokenService>(Lifestyle.Scoped);

            _container.Verify();
        }
コード例 #44
0
        private static Container setupIocContainer(SetupArgs args)
        {
            var container = new Container();

            container.Register <ILogger>(() => LogManager.GetLogger(nameof(LiteDbApplication)), Lifestyle.Singleton);
            container.Register(() => args, Lifestyle.Singleton);
            container.RegisterPackages(new[] { typeof(LiteDbApplication).Assembly });
            container.RegisterPackages(new[] { args.Assembly });

            container.Verify(VerificationOption.VerifyAndDiagnose);

            return(container);
        }
コード例 #45
0
        public static void RegisterInterfacesAndType <T>(this Container container, IEnumerable <Type> types)
        {
            var ifaceType = typeof(T);

            foreach (var s in types)
            {
                container.Register(s, s);
                foreach (var i in s.GetInterfaces().Where(x => Predicate(x, ifaceType)))
                {
                    container.Register(i, s);
                }
            }
        }
コード例 #46
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public static void ConfigureDependencies(this IAppBuilder app)
        {
            // 1. Create a new Simple Injector container
            var container = new SimpleInjector.Container();

            // 2. Configure the container (register)
            container.Register <ILoggingService, LoggingService>(Lifestyle.Transient);
            container.Register <IDataRepository, DataRepository>(Lifestyle.Singleton);
            container.Register <ILookupService, LookupService>(Lifestyle.Transient);
            container.Register <ICostCalculationService, CostCalculationService>(Lifestyle.Transient);

            System.Web.Mvc.DependencyResolver.SetResolver(new SimpleInjector.Integration.Web.Mvc.SimpleInjectorDependencyResolver(container));
        }
コード例 #47
0
        /// <inheritdoc />
        public void RegisterServices(Container container)
        {
            var registration = Lifestyle.Singleton.CreateRegistration <Mediators.Mediator>(container);

            container.AddRegistration <IMediator>(registration);
            container.AddRegistration <IMessageRecipientsRegistrar>(registration);
            container.AddRegistration <IPipelineProcessorsRegistrar>(registration);

            container.Register <IPreProcessorService, PreProcessorService>(Lifestyle.Singleton);
            container.Register <IEventCollectorFactory, EventCollectorFactory>(Lifestyle.Singleton);
            container.Collection.Register <IMessageHandler>(GetType().Assembly);
            container.Collection.Register <IMessageHandlerAsync>(GetType().Assembly);

            container.Register <MediatorRegistrar>(Lifestyle.Singleton);
        }
コード例 #48
0
        private static void InitializeContainer(Container container)
        {
            BootStrapperApplication.RegisterServices(container);
            BootStrapperDomain.RegisterServices(container);
            BootStrapperInfra.RegisterServices(container);

            container.Register <IUserStore <ApplicationUser> >(() => new UserStore <ApplicationUser>(new ApplicationDbContext()), Lifestyle.Scoped);
            container.Register <IRoleStore <IdentityRole, string> >(() => new RoleStore <IdentityRole>(), Lifestyle.Scoped);
            container.Register <IAuthenticationManager>(() => AdvancedExtensions.IsVerifying(container)
                    ? new OwinContext(new Dictionary <string, object>()).Authentication
                    : HttpContext.Current.GetOwinContext().Authentication, Lifestyle.Scoped);

            container.Register <ApplicationUserManager>(Lifestyle.Scoped);
            container.Register <ApplicationSignInManager>(Lifestyle.Scoped);
        }
コード例 #49
0
        public static void Register()
        {
            var container = new SimpleInjector.Container();

            //Daha sonra config dosyasından alınacak.
            container.Register <IDbConnection>(() => new NpgsqlConnection("Host=localhost;Username=postgres;Password=1234;Database=postgres"), Lifestyle.Singleton);
            container.Register <IBookService, BookService>(Lifestyle.Transient);
            container.Register <IBookRepository, BookRepository>(Lifestyle.Transient);

            // 3. Optionally verify the container's configuration.
            container.Verify();

            // 4. Store the container for use by the application
            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);
        }
コード例 #50
0
        private static bool Bootstrap()
        {
            container = new Container();
            var connectionstring = LocalDbHelper.GetConnectionString();

            if (string.IsNullOrEmpty(connectionstring))
            {
                MessageBox.Show("De database kon niet worden aangemaakt of gevonden. Mogelijk is deze niet geïnstalleerd. Installeer SqlLocalDB.MSI", "Database niet gevonden", MessageBoxButtons.OK);
                return(false);
            }


            container.Register <IDataService>(() => new DataService(connectionstring), Lifestyle.Singleton);
            container.Register <TopXConverter>();
            return(true);
        }
コード例 #51
0
ファイル: EntityTestBase.cs プロジェクト: pixstock-p/pixstock
        protected Scope InitializeFact(bool isUsingInMemoryDatabase = true)
        {
            Scope scope = null;

            lock (TestThreadLocker)
            {
                int threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;

                InitializeContainer(threadId);
                if (isUsingInMemoryDatabase)
                {
                    container.Register <IAppDbContext, TestAppDbContext>(Lifestyle.Scoped);
                    container.Register <IThumbnailDbContext, TestThumbnailDbContext>(Lifestyle.Scoped);
                }
                else
                {
                    container.Register <IAppDbContext, AppDbContext>(Lifestyle.Scoped);
                    container.Register <IThumbnailDbContext, ThumbnailDbContext>(Lifestyle.Scoped);
                }

                container.Verify();



                scope = AsyncScopedLifestyle.BeginScope(container);

                var context = (AppDbContext)container.GetInstance <IAppDbContext>();

                if (isUsingInMemoryDatabase)
                {
                    // In-Memory Database
                    context.Database.OpenConnection();
                    context.Database.EnsureCreated();
                }

                var app = (ApplicationContextImpl)container.GetInstance <IApplicationContext>();
                app.Initialize();

                System.Console.WriteLine("アプリケーションフォルダ=" + app.ApplicationDirectoryPath);

                ImportInitializeData(threadId, container);

                System.Console.WriteLine("データベースの初期化を完了しました。");
            }

            return(scope);
        }
コード例 #52
0
        private static void InitializeContainer(Container container)
        {
            BootStrapperApplication.RegisterServices(container);
            BootStrapperDomain.RegisterServices(container);
            BootStrapperInfra.RegisterServices(container);

            container.Register <IUserStore <ApplicationUser> >();
        }
コード例 #53
0
        /// <summary>
        /// Register the type mapping with the container, with the given <see cref="LifetimeType" />.
        /// </summary>
        /// <param name="serviceType"><see cref="System.Type" /> of the service that will be requested.</param>
        /// <param name="implementationType"><see cref="System.Type" /> of the implementation that will be returned.</param>
        /// <param name="lifetime">The <see cref="LifetimeType" /> of the service.</param>
        /// <returns>The <see cref="IContainerProvider" /> object that this method was called on.</returns>
        /// <exception cref="ArgumentException">Thrown when the implementation type does not inherit from IPerRequestTask and lifetime is PerRequest.</exception>
        public override IContainerProvider RegisterType(Type serviceType, Type implementationType, LifetimeType lifetime)
        {
            if (lifetime == LifetimeType.Singleton)
            {
                container.Register(serviceType, implementationType, Lifestyle.Singleton);
            }
            else if (lifetime == LifetimeType.Transient)
            {
                container.Register(serviceType, implementationType, Lifestyle.Transient);
            }
            else
            {
                throw new Exception("Unknown lifetime type.");
            }

            return(this);
        }
コード例 #54
0
ファイル: IocTest.cs プロジェクト: toneylan/Tamos.Origin
        public void PerformTest()
        {
            var spCont = new SimpleInjector.Container();

            spCont.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
            spCont.Register <ICentralConfigProvider, TestConfigProvider>(Lifestyle.Scoped);
            using (AsyncScopedLifestyle.BeginScope(spCont))
            {
                spCont.GetInstance <ICentralConfigProvider>();
            }

            var autofacBd = new Autofac.ContainerBuilder();

            autofacBd.RegisterType <TestConfigProvider>().As <ICentralConfigProvider>();
            var autofac = autofacBd.Build();

            using (var scope = autofac.BeginLifetimeScope())
            {
                autofac.Resolve <ICentralConfigProvider>();
            }


            var count = 1000;

            Console.WriteLine($"Start test {count} times: -----------------------");

            //----SimpleInjector
            var task = Task.Run(() => TestUtil.RunWatch("SimpleInjector", count, () =>
            {
                using (AsyncScopedLifestyle.BeginScope(spCont))
                {
                    var siIns = spCont.GetInstance <ICentralConfigProvider>();
                }
            }));

            //-------------------------------------------------
            var task1 = Task.Run(() => TestUtil.RunWatch("Autofac", count, () =>
            {
                using (var scope = autofac.BeginLifetimeScope())
                {
                    autofac.Resolve <ICentralConfigProvider>();
                }
            }));

            //----SimpleInjector

            /*var task = Task.Run(() => TestUtil.RunWatch("Castle", count, () =>
             * {
             *  using (castle.BeginScope())
             *  {
             *      castle.Resolve<ICentralConfigProvider>();
             *  }
             * }));*/

            task.Wait();
            task1.Wait();
        }
コード例 #55
0
ファイル: Program.cs プロジェクト: Sakul/experiments
        static void Main(string[] args)
        {
            // Create a new container
            var container = new SimpleInjector.Container();

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

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

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

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

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

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

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

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

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

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

            var depenOnB = container.GetInstance <AService>();
            var depenOnA = container.GetInstance <BService>();
        }
コード例 #56
0
        public static void LetThereBeIoC()
        {
            container = new Container();
            IoC       = container;
            IoC.Register <IModuleBinder, ModuleReferenceKeyBinder>(Lifestyle.Transient);
            IoC.Register <IObjectBinder, ReferenceKeyBinder>(Lifestyle.Transient);
            IoC.Register <IBindableObject, ModuleObject>(Lifestyle.Transient);
            IoC.Register <IContextData, ModuleContextArray>(Lifestyle.Transient);
            IoC.Register <ISerializableModuleIdManager, ModuleIdManager>(Lifestyle.Transient);
            IoC.Register <ISerializableIdManager, ObjectIdManager>(Lifestyle.Transient);

            //Batch register is not possible for ISerializableId<T> for all T because it must
            //have more than one constructor.
            IoC.Register <ISerializableId <List <Tuple <string, int, int, byte[]> > > >(() => new ModuleId());
            IoC.Register <ISerializableId <byte[]> >(() => new ObjectId());
            IoC.Register <IContextManager, ModuleContextManager>(Lifestyle.Transient);

            IoC.Register <IDocumentManager, DocumentManager>(Lifestyle.Singleton);
        }
コード例 #57
0
        public static void Register()
        {
            // Create the container as usual.
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

            // Register your types, for instance:
            container.Register <IPetRepository, PetRepository>(Lifestyle.Scoped);
            container.Register <IPetService, PetService>(Lifestyle.Scoped);
            container.Register <ApplicationDbContext, ApplicationDbContext>(Lifestyle.Scoped);

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

            container.Verify();

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
コード例 #58
0
        public Form1()
        {
            InitializeComponent();

            CustomerContainer = new Container();
            CustomerContainer
            .Register <ICustomer, SqlCustomerData>(Lifestyle.Singleton);

            CustomerContainer.Verify();
        }
コード例 #59
0
 private void RegisterManualResetEvent(ref SimpleInjector.Container container, ManualResetEventSlim resetEvent)
 {
     try
     {
         container.Register <ManualResetEventSlim>(() => resetEvent);
     }
     catch (Exception ex)
     {
         throw;
     }
 }
コード例 #60
0
        public static void RegisterDependencies()
        {
            // Create a new Simple Injector container
            var container = new SimpleInjector.Container();

            // Set the scoped lifestyle one directly after creating the container
            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

            // Configure the container (register)
            container.Register <IPolicyService, PolicyService>(Lifestyle.Scoped);
            container.Register <IDataAccess, DataAccess>(Lifestyle.Scoped);
            container.Register <IKexpertDb, KexpertDb>(Lifestyle.Scoped);

            // Optionally verify the container's configuration.
            container.Verify();

            // Store the container for use by the application
            DependencyResolver.SetResolver(
                new SimpleInjectorDependencyResolver(container));
        }