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(); }
private static void Bootstrap() { container = new SimpleInjector.Container(); container.Register <IUsersService, UserServices>(); container.Register <Iunitofwork, SampleContext>(); container.Register <frm_AddEdit>(); }
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(); }
/// <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; }); }
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(); }
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 ); }
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"); }
public void RegisterDependencies(Container container) { container.Register <ITaskRepository, TaskRepository>(); container.Register <NewLeadService, NewLeadService>(); container.Verify(); }
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; }
public void RegisterServices(Container container, CompositionRootSettings settings) { if (settings.ViewModelAssemblies == null) return; container.RegisterSingleton<IProcessViewModels, ViewModelProcessor>(); container.Register(typeof(IHandleViewModel<>), settings.ViewModelAssemblies); container.Register(typeof(IHandleViewModel<,>), settings.ViewModelAssemblies); container.RegisterDecorator( typeof(IHandleViewModel<>), typeof(ViewModelLifetimeScopeDecorator<>), Lifestyle.Singleton ); container.RegisterDecorator( typeof(IHandleViewModel<,>), typeof(ViewModelWithArgumentLifetimeScopeDecorator<,>), Lifestyle.Singleton ); container.RegisterDecorator( typeof(IHandleViewModel<,>), typeof(ViewModelWithArgumentNotNullDecorator<,>), Lifestyle.Singleton ); }
public static 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(); }
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"))); }
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); }
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); }
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)); }
public override void Configure(Container container) { container.Register<IConsole, SystemConsole>(); container.Register<IThreadService, ThreadService>(); ViewEngines.Add<RazorViewEngine>(); }
/// <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)); }
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); }
private static void InitializeContainer(Container container) { container.Register<IConfigurationProvider, AppSettingsConfigurationProvider>(); container.Register<IMetadataProvider, TwitterSecurityTokenServiceConfiguration>(); container.Register<SecurityTokenServiceConfiguration, TwitterSecurityTokenServiceConfiguration>(); container.Register<IIdentityProvider, TwitterSecurityTokenService>(); }
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)); }
public void RegisterServices(Container container) { container.RegisterWebApiRequest<IDbFactory>(() => new DbFactory(ConfigurationManager.ConnectionStrings["People"].ConnectionString)); container.Register<IPeopleRepository, PeopleRepository>(); container.Register<IPeopleService, PeopleService>(); container.Verify(); }
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); }
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); }
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 }
/// <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>(); }
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); }
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()); }
public void Register(Type concrete, Contracts.Lifestyle lifestyle) { if (_child) { return; } _container.Register(concrete, concrete, ConvertLifestyle(lifestyle)); }
public void TestFixtureSetUp() { _container = new Container(); //Register services _container.Register<TestService>(); _container.Register<ITestDependency, TestDependency>(); }
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>(); }
public void Step4() { var container = new Container(); container.Register<IDependency1>(() => new Dependency1()); container.Register<IService1, Service1a>(); container.Verify(VerificationOption.VerifyAndDiagnose); }
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); }
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); }
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()); }
private static void InitializeContainer(Container container) { // For instance: // container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped); container.Register<AmigoBusiness,AmigoBusiness>(); container.Register<AmigoDAO,AmigoDAO>(); }
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; }
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); }
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>(); }
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); }
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); }
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); }
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); }
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(); }
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); }
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); } } }
// 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)); }
/// <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); }
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); }
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); }
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); }
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); }
private static void InitializeContainer(Container container) { BootStrapperApplication.RegisterServices(container); BootStrapperDomain.RegisterServices(container); BootStrapperInfra.RegisterServices(container); container.Register <IUserStore <ApplicationUser> >(); }
/// <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); }
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(); }
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>(); }
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); }
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)); }
public Form1() { InitializeComponent(); CustomerContainer = new Container(); CustomerContainer .Register <ICustomer, SqlCustomerData>(Lifestyle.Singleton); CustomerContainer.Verify(); }
private void RegisterManualResetEvent(ref SimpleInjector.Container container, ManualResetEventSlim resetEvent) { try { container.Register <ManualResetEventSlim>(() => resetEvent); } catch (Exception ex) { throw; } }
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)); }