private static void StartMain() { WebsiteMapper.Initialize(); // 1. Create a new Simple Injector container var container = new Container(); // register unit of work / context by request var webLifestyle = new WebRequestLifestyle(); container.Register <IUnitOfWork, SqlUnitOfWork>(webLifestyle); container.Register <ILoginBLL, LoginBLL>(); container.Register <IPageBLL, PageBLL>(); container.Register <IMstBarangJadiBLL, MstBarangJadiBLL>(); container.Register <IMstBahanBakuBLL, MstBahanBakuBLL>(); container.Register <IMstWilayahBLL, MstWilayahBLL>(); container.Register <ITrnSpbBLL, TrnSpbBLL>(); container.Register <ITrnDoBLL, TrnDoBLL>(); container.Register <ITrnPengirimanBLL, TrnPengirimanBLL>(); container.Register <ITrnHasilProduksiBLL, TrnHasilProduksiBLL>(); container.Register <IRptOutstandingBLL, RptOutstandingBLL>(); // 3. Optionally verify the container's configuration. container.Verify(); // 4. Store the container for use by Page classes. _container = container; }
public static void Register() { #region Config // Create the container as usual. var container = new Container(); var services = GlobalConfiguration.Configuration.Services; var controllerTypes = services.GetHttpControllerTypeResolver() .GetControllerTypes(services.GetAssembliesResolver()); // register Web API controllers (important! http://bit.ly/1aMbBW0) foreach (var controllerType in controllerTypes) { container.Register(controllerType); } #endregion var perRequestLifeTime = new WebRequestLifestyle(); container.Register <BreezeRepository>(perRequestLifeTime); container.Register <BreezeContextProvider>(perRequestLifeTime); // Verify the container configuration container.Verify(); // Register the dependency resolver. GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); }
public void WhenWebRequestEnds_BothAScopeEndsActionAndDisposableIntanceRegistered_InstancesGetDisposedLast() { // Arrange string expectedOrder = "[scope ending] [instance disposed]"; string actualOrder = string.Empty; ScopedLifestyle lifestyle = new WebRequestLifestyle(); var container = new Container(); var scope = new HttpContextScope(); try { lifestyle.RegisterForDisposal(container, new DisposableAction(() => actualOrder += "[instance disposed]")); lifestyle.WhenScopeEnds(container, () => actualOrder += "[scope ending] "); } finally { // Act scope.Dispose(); } // Assert Assert.AreEqual(expectedOrder, actualOrder, "Instances should get disposed after all 'scope ends' actions are executed, since those " + "delegates might still need to access those instances."); }
public static void ConfigureMvc(this Container container) { var lifestyle = new WebRequestLifestyle(); container.RegisterDependencies(lifestyle); container.RegisterMvcControllers(Assembly.GetExecutingAssembly()); container.RegisterMvcIntegratedFilterProvider(); DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container)); }
public static void RegisterPerWebRequest <TService>(this Container container, Func <TService> instanceCreator, bool disposeInstanceWhenWebRequestEnds) where TService : class { Requires.IsNotNull(container, nameof(container)); Requires.IsNotNull(instanceCreator, nameof(instanceCreator)); container.Register <TService>(instanceCreator, WebRequestLifestyle.Get(disposeInstanceWhenWebRequestEnds)); }
public void WhenCurrentRequestEnds_OutsideTheContextOfAHttpRequest_ThrowsExpectedException() { // Act Action action = () => WebRequestLifestyle.WhenCurrentRequestEnds(new Container(), () => { }); // Assert AssertThat.ThrowsWithExceptionMessageContains <InvalidOperationException>( "This method can only be called within the context of an active Web Request.", action); }
private static void InitializeContainer(Container container) { // For instance: // container.Register<IUserRepository, SqlUserRepository>(); WebRequestLifestyle lifestyle = new WebRequestLifestyle(true); container.Register(() => new DpapiDataProtectionProvider()); container.Register(() => new UserContext(), lifestyle); container.Register(() => new UserStore <User>(container.GetInstance <UserContext>()), lifestyle); container.Register(() => new UserManager <User>(container.GetInstance <UserStore <User> >()), lifestyle); }
public void WhenCurrentRequestEnds_WithValidArgumentsInHttpContext_Succeeds() { // Arrange var validContainer = new Container(); Action validAction = () => { }; using (new HttpContextScope()) { // Act WebRequestLifestyle.WhenCurrentRequestEnds(validContainer, validAction); } }
public void WhenScopeEnds_OutsideTheContextOfAHttpRequest_ThrowsExpectedException() { // Arrange ScopedLifestyle lifestyle = new WebRequestLifestyle(); // Act Action action = () => lifestyle.WhenScopeEnds(new Container(), () => { }); // Assert AssertThat.ThrowsWithExceptionMessageContains <InvalidOperationException>( "This method can only be called within the context of an active (Web Request) scope.", action); }
private static void InitializeContainer(Container container) { //per web request lifestyle var webLifestyle = new WebRequestLifestyle(); container.Register <IDatabaseFactory, DatabaseFactory>(webLifestyle); container.Register <IUnitOfWork, UnitOfWork>(webLifestyle); //start defining services container.Register <IUserService, UserService>(webLifestyle); //register generic repository container.Register(typeof(IRepository <>), typeof(Repository <>), webLifestyle); }
public static void RegisterDependencies(HttpApplication app) { Container container = new Container(); WebRequestLifestyle perWebRequest = new WebRequestLifestyle(); container.Register <IEntityTypeManager, UserEntitiesManager>(Lifestyle.Singleton); container.RegisterOpenGeneric(typeof(IRepository <>), typeof(GenericRepository <>), perWebRequest); container.Register <DbContext, UserEntitiesContext>(perWebRequest); container.Verify(); DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container)); app.Application[ContainerKeyInApplication] = container; }
public void RegisterServices(Container container) { var webRequestLifestyle = new WebRequestLifestyle(); container.Register(() => new BloggableDbContext(AppSettingConstants.DefaultDbConnectionName), webRequestLifestyle); container.Register <DbContext>(container.GetInstance <BloggableDbContext>, webRequestLifestyle); container.Register <IdentityDbContext <User> >(container.GetInstance <BloggableDbContext>, webRequestLifestyle); container.Register(typeof(IRepository <>), typeof(EfRepository <>), webRequestLifestyle); container.Register(typeof(IDeletableEntityRepository <>), typeof(EfDeletableEntityRepository <>), webRequestLifestyle); container.Register <IEntityKeyTypesProvider, EfEntityKeyTypesProvider>(); }
public static void Register() { // 1. Create a new Simple Injector container var container = new Container(); var webLifestyle = new WebRequestLifestyle(); // 2. Configure the container (register) container.RegisterPerWebRequest <MyDataContext>( () => new MyDataContext( ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString )); container.RegisterPerWebRequest <LangId>( () => new LangId()); container.RegisterPerWebRequest <IUow>( () => new Uow(container.GetInstance <MyDataContext>() , container.GetInstance <LangId>().Lang_Id , container.GetInstance <LangId>().Center_Id)); //container.RegisterPerWebRequest<IUow>( // () => new Uow(container.GetInstance<MyDataContext>())); //container.Register<IUow>( // () => new Uow(container.GetInstance<MyDataContext>()), webLifestyle); var assembly = typeof(IService).Assembly; var registrations = from type in assembly.GetExportedTypes() where type.GetInterfaces().Contains(typeof(IService)) && type.IsClass && !type.IsAbstract//CityService select new { Service = type.GetInterfaces().Where(i => i.Name.Equals("I" + type.Name)).First(), Implementation = type }; foreach (var reg in registrations) { //reg.Service: ICityService //reg.Implementation: CityService //container.RegisterSingle(reg.Service, reg.Implementation); //container.Register(reg.Service, reg.Implementation, webLifestyle); if (!reg.Implementation.Name.StartsWith("Service")) { container.Register(reg.Service , () => Activator.CreateInstance(reg.Implementation, container.GetInstance <IUow>()) , webLifestyle); } } // 3. Optionally verify the container's configuration. container.Verify(); // 4. Store the container for use by Page classes. _container = container; }
public void WhenCurrentRequestEnds_WithNullContainer_ThrowsExpectedException() { // Arrange Container invalidContainer = null; using (new HttpContextScope()) { // Act Action action = () => WebRequestLifestyle.WhenCurrentRequestEnds(invalidContainer, () => { }); // Assert AssertThat.ThrowsWithParamName <ArgumentNullException>("container", action); } }
public void RegisterForDisposal_WithValidArgumentsInHttpContext_Succeeds() { // Arrange ScopedLifestyle lifestyle = new WebRequestLifestyle(); var validContainer = new Container(); IDisposable validInstance = new DisposableCommand(); using (new HttpContextScope()) { // Act lifestyle.RegisterForDisposal(validContainer, validInstance); } }
/// <summary> /// Registers the supplied <paramref name="disposable"/> for disposal when the current web request /// ends. /// </summary> /// <example> /// The following example registers a <b>DisposableServiceImpl</b> type as transient (a new instance /// will be returned every time) and registers an initializer for that type that will ensure that /// that instance will be disposed when the web request ends: /// <code lang="cs"><![CDATA[ /// container.Register<IService, ServiceImpl>(); /// container.RegisterInitializer<ServiceImpl>(SimpleInjectorWebExtensions.RegisterForDisposal); /// ]]></code> /// </example> /// <param name="disposable">The disposable.</param> /// <exception cref="ArgumentNullException"> /// Thrown when the given <paramref name="disposable"/> is a null reference.</exception> /// <exception cref="InvalidOperationException">Thrown when the <see cref="HttpContext.Current"/> /// returns null.</exception> public static void RegisterForDisposal(IDisposable disposable) { Requires.IsNotNull(disposable, "disposable"); var context = HttpContext.Current; if (context == null) { throw new InvalidOperationException( "This method can only be called in the context of a web request."); } WebRequestLifestyle.RegisterForDisposal(disposable, context); }
public void WhenCurrentRequestEnds_WithNullAction_ThrowsExpectedException() { // Arrange Action invalidAction = null; using (new HttpContextScope()) { // Act Action action = () => WebRequestLifestyle.WhenCurrentRequestEnds(new Container(), invalidAction); // Assert AssertThat.ThrowsWithParamName <ArgumentNullException>("action", action); } }
public static void Setup() { var container = new Container(); var perRequest = new WebRequestLifestyle(); var dataAccessAssembly = typeof(CinemaContext).Assembly; var moviesAssembly = typeof(Seat).Assembly; var promotionsAssembly = typeof(Promotions.Promotion).Assembly; var applicationAssembly = typeof(RenamePromotionCommand).Assembly; var connectionString = ConfigurationManager.ConnectionStrings["DDDCinema"].ConnectionString; container.Register(() => new CinemaContext(connectionString), perRequest); container.Register(() => new PromotionsContext(connectionString), perRequest); container.Register(() => new InfrastructureContext(connectionString), perRequest); container.Register(() => new DDDCinemaReadonly(), perRequest); var userProviderRegistration = Lifestyle.Singleton.CreateRegistration <ContextUserProvider>(container); container.AddRegistration(typeof(ICurrentUserProvider), userProviderRegistration); container.AddRegistration(typeof(ContextUserProvider), userProviderRegistration); container.Register <IWinChanceCalculatorFactory, SimpleInjectorWinChanceCalculatorFactory>(Lifestyle.Singleton); foreach (var repositorType in dataAccessAssembly.GetExportedTypes() .Where(t => t.Name.Contains("Repository"))) { container.Register(repositorType.GetInterfaces().Single(), repositorType, perRequest); } container.RegisterDecorator(typeof(ICommandHandler <LoginCommand>), typeof(AuditingLoginCommandHandler)); container.RegisterDecorator(typeof(ICommandHandler <>), typeof(AuditingCommandHandler <>), p => !p.AppliedDecorators.Any(t => t.Name.Contains("Auditing"))); container.RegisterDecorator(typeof(ICommandHandler <>), typeof(CinemaTransactionalCommandHandler <>)); container.RegisterDecorator(typeof(ICommandHandler <>), typeof(PromotionTransactionalCommandHandler <>)); container.RegisterDecorator(typeof(ICommandHandler <>), typeof(InfrastructureTransactionalCommandHandler <>)); container.Register(typeof(ICommandHandler <>), new[] { applicationAssembly }); container.RegisterCollection(typeof(INotificationSender), new[] { moviesAssembly }); var registration = perRequest.CreateRegistration <SendNotificationWhenSeatTaken>(container); container.AppendToCollection(typeof(IDomainEventHandler <>), typeof(AuditOccurrenceEventHandler <>)); container.RegisterCollection(typeof(IDomainEventHandler <>), moviesAssembly, promotionsAssembly); container.RegisterDecorator(typeof(IDomainEventHandler <>), typeof(AuditingEventHandler <>), p => !p.ImplementationType.Name.Contains("Audit")); container.Register <List <INotificationSender> >(() => container.GetAllInstances <INotificationSender>().ToList(), perRequest); container.Register <ISheduler, SagaTimeoutSheduler>(perRequest); container.Register <IPromotionCodeGenerator, PromoCodeGenerator>(perRequest); DomainEventBus.Current = new SimpleInjectorEventBus(container); DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container)); }
public void RegisterServices(Container container) { var webRequestLifestyle = new WebRequestLifestyle(); container.Register <IUserStore <User> >( () => new UserStore <User>(container.GetInstance <IdentityDbContext <User> >()), webRequestLifestyle); container.Register( () => container.IsVerifying() ? new OwinContext(new Dictionary <string, object>()).Authentication : HttpContext.Current.GetOwinContext().Authentication, webRequestLifestyle); container.Register <ApplicationUserManager>(webRequestLifestyle); container.Register <ApplicationSignInManager>(webRequestLifestyle); }
public void RegisterForDisposal_OutsideTheContextOfAHttpRequest_ThrowsExpectedException() { // Arrange ScopedLifestyle lifestyle = new WebRequestLifestyle(); var validContainer = new Container(); var validInstance = new DisposableCommand(); // Act Action action = () => lifestyle.RegisterForDisposal(validContainer, validInstance); // Assert AssertThat.ThrowsWithExceptionMessageContains <InvalidOperationException>( "This method can only be called within the context of an active Web Request.", action); }
private void SetupIocContainer() { var container = new Container(); container.RegisterMvcControllers(Assembly.GetExecutingAssembly()); container.RegisterMvcIntegratedFilterProvider(); var lifestyle = new WebRequestLifestyle(); container.RegisterSingle <ILogger, NLogLogger>(); container.RegisterSingle <ICache, MemoryCache>(); container.Register <IAuthenticationManager>(() => HttpContext.Current.GetOwinContext().Authentication); container.Register <IHomeModelBuilder, HomeModelBuilder>(lifestyle); DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container)); }
public void RegisterForDisposal_WithNullAction_ThrowsExpectedException() { // Arrange ScopedLifestyle lifestyle = new WebRequestLifestyle(); IDisposable invalidInstance = null; using (new HttpContextScope()) { // Act Action action = () => lifestyle.RegisterForDisposal(new Container(), invalidInstance); // Assert AssertThat.ThrowsWithParamName <ArgumentNullException>("disposable", action); } }
public void RegisterForDisposal_WithNullContainer_ThrowsExpectedException() { // Arrange ScopedLifestyle lifestyle = new WebRequestLifestyle(); Container invalidContainer = null; using (new HttpContextScope()) { // Act Action action = () => lifestyle.RegisterForDisposal(invalidContainer, new DisposableCommand()); // Assert AssertThat.ThrowsWithParamName <ArgumentNullException>("container", action); } }
private static void InitializeContainer(Container container) { Lifestyle ls = new WebRequestLifestyle(); container.Register <IApplicationDbContext, ApplicationEntities>(ls); container.Register <IApplicationUserManager, ApplicationUserManager>(ls); container.Register <IApplicationRoleManager, ApplicationRoleManager>(ls); container.Register <IAccessControl, AccessControlLogic>(ls); container.Register <AdminParticipant>(ls); container.Register <ClientParticipant>(ls); container.Register <RentContract>(ls); container.Register <IApplicationConfig, ApplicationConfig>(Lifestyle.Singleton); container.Register(typeof(IRepository <,>), typeof(EFRepository <,>), ls); }
public void Verify_WhenCurrentRequestEndsCalledDuringVerificationOutsideAnHttpContext_Succeeds() { // Arrange bool initializerCalled = false; var container = new Container(); container.Register <DisposableCommand>(); container.RegisterInitializer <DisposableCommand>(command => { WebRequestLifestyle.WhenCurrentRequestEnds(container, () => command.Dispose()); initializerCalled = true; }); // Act container.Verify(VerificationOption.VerifyOnly); // Arrange Assert.IsTrue(initializerCalled); }
public void RegisterServices(Container container) { var webRequestLifestyle = new WebRequestLifestyle(); // Generic types container.Register( typeof(IDeletableEntityAdministrationService <>), typeof(DeletableEntityAdministrationService <>), webRequestLifestyle); container.Register(typeof(IAdministrationService <>), typeof(AdministrationService <>), webRequestLifestyle); // Non-generic types var serviceAssemblies = new[] { typeof(IService).Assembly, Assembly.Load(AssemblyConstants.ServicesData), Assembly.Load(AssemblyConstants.ServicesAdministration), }; var nonGenericTypeServiceRegistrationsInfo = serviceAssemblies .SelectMany(a => a.GetExportedTypes()) .Where(t => typeof(IService).IsAssignableFrom(t) && !t.IsAbstract && !t.IsGenericTypeDefinition) .Select(t => new { ConcreteType = t, ServiceTypes = t .GetInterfaces() .Where(i => i.IsPublic && i != typeof(IService) && !i.GenericTypeArguments.Any()) }) .ToList(); foreach (var registration in nonGenericTypeServiceRegistrationsInfo) { registration.ServiceTypes.ForEach( serviceType => container.Register(serviceType, registration.ConcreteType, webRequestLifestyle)); } // Custom registrations container.Register(() => AutoMapperConfig.MapperConfiguration.CreateMapper(), webRequestLifestyle); }
public static void RegisterDependencies(Container container) { var webRequestLifeStyle = new WebRequestLifestyle(); container.RegisterPersistenceDependencies(webRequestLifeStyle); container.RegisterModelDependencies(webRequestLifeStyle); container.Register <SignInService, SignInService>(webRequestLifeStyle); container.Register <UserManager <Administrator>, UserManager <Administrator> >(webRequestLifeStyle); container.Register <UserManager <Advertiser>, UserManager <Advertiser> >(webRequestLifeStyle); container.Register <IUserStore <Administrator>, AdministratorStore>(webRequestLifeStyle); container.Register <IUserStore <Advertiser>, AdvertiserStore>(webRequestLifeStyle); container.Register <IAuthenticationManager>(() => HttpContext.Current.GetOwinContext().Authentication, webRequestLifeStyle); container.RegisterWebApiControllers(GlobalConfiguration.Configuration); GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); //container.Verify(); }
protected override void OnApplicationStarted(object sender, EventArgs e) { SqlUnitOfWork.DbContext = new LearningContext(); SqlLamBase._defaultAdapter = new UmbracoQueryAdapter(); var webLifestyle = new WebRequestLifestyle(); var container = new Container(); container.Register <ILogger, NLogLogger>(webLifestyle); container.Register <IProfileRepository, ProfileRepository>(); container.Register <IMessageRepository, MessageRepository>(); container.Register <IProfileService, ProfileService>(); container.Register <IUnitOfWork, SqlUnitOfWork>(webLifestyle); container.Verify(); DependencyResolver.SetResolver(new VxSimpleInjectorResolver(container)); base.OnApplicationStarted(sender, e); Voxteneo.Core.Mvc.VoxStartup.RegisterRoutes += VoxStartupOnRegisterRoutes; Voxteneo.Core.Mvc.VoxStartup.Initialize(); // Your code here }
public void Verify_RegisterForDisposalCalledDuringVerificationOutsideAnHttpContext_Succeeds() { // Arrange ScopedLifestyle lifestyle = new WebRequestLifestyle(); bool initializerCalled = false; var container = new Container(); container.Register <DisposableCommand>(); container.RegisterInitializer <DisposableCommand>(command => { lifestyle.RegisterForDisposal(container, command); initializerCalled = true; }); // Act container.Verify(VerificationOption.VerifyOnly); // Arrange Assert.IsTrue(initializerCalled); }
private static Lifestyle ResolveLifestyle(BindingLifecycle lifecycle) { var lifestyle = Lifestyle.Transient; switch (lifecycle) { case BindingLifecycle.Singleton: lifestyle = Lifestyle.Singleton; break; case BindingLifecycle.Request: lifestyle = new WebRequestLifestyle(); break; case BindingLifecycle.Transient: lifestyle = Lifestyle.Transient; break; case BindingLifecycle.Thread: throw new NotSupportedException("Ref documentation: This lifestyle is deliberately left out of Simple Injector because it is considered to be harmful. Instead of using Per Thread lifestyle, you will usually be better of using one of the Scoped lifestyles."); } return(lifestyle); }
public void RegisterForDisposal_WithNullAction_ThrowsExpectedException() { // Arrange ScopedLifestyle lifestyle = new WebRequestLifestyle(); IDisposable invalidInstance = null; using (new HttpContextScope()) { // Act Action action = () => lifestyle.RegisterForDisposal(new Container(), invalidInstance); // Assert AssertThat.ThrowsWithParamName<ArgumentNullException>("disposable", action); } }
public void RegisterForDisposal_WithNullContainer_ThrowsExpectedException() { // Arrange ScopedLifestyle lifestyle = new WebRequestLifestyle(); Container invalidContainer = null; using (new HttpContextScope()) { // Act Action action = () => lifestyle.RegisterForDisposal(invalidContainer, new DisposableCommand()); // Assert AssertThat.ThrowsWithParamName<ArgumentNullException>("container", action); } }
public void RegisterForDisposal_OutsideTheContextOfAHttpRequest_ThrowsExpectedException() { // Arrange ScopedLifestyle lifestyle = new WebRequestLifestyle(); var validContainer = new Container(); var validInstance = new DisposableCommand(); // Act Action action = () => lifestyle.RegisterForDisposal(validContainer, validInstance); // Assert AssertThat.ThrowsWithExceptionMessageContains<InvalidOperationException>( "This method can only be called within the context of an active Web Request.", action); }
public void Verify_RegisterForDisposalCalledDuringVerificationOutsideAnHttpContext_Succeeds() { // Arrange ScopedLifestyle lifestyle = new WebRequestLifestyle(); bool initializerCalled = false; var container = new Container(); container.Register<DisposableCommand>(); container.RegisterInitializer<DisposableCommand>(command => { lifestyle.RegisterForDisposal(container, command); initializerCalled = true; }); // Act container.Verify(VerificationOption.VerifyOnly); // Arrange Assert.IsTrue(initializerCalled); }
public void WhenScopeEnds_WithValidArgumentsInHttpContext_Succeeds() { // Arrange ScopedLifestyle lifestyle = new WebRequestLifestyle(); var validContainer = new Container(); Action validAction = () => { }; using (new HttpContextScope()) { // Act lifestyle.WhenScopeEnds(validContainer, validAction); } }
public void WhenScopeEnds_WithNullAction_ThrowsExpectedException() { // Arrange ScopedLifestyle lifestyle = new WebRequestLifestyle(); Action invalidAction = null; using (new HttpContextScope()) { // Act Action action = () => lifestyle.WhenScopeEnds(new Container(), invalidAction); // Assert AssertThat.ThrowsWithParamName<ArgumentNullException>("action", action); } }
public void WhenScopeEnds_OutsideTheContextOfAHttpRequest_ThrowsExpectedException() { // Arrange ScopedLifestyle lifestyle = new WebRequestLifestyle(); // Act Action action = () => lifestyle.WhenScopeEnds(new Container(), () => { }); // Assert AssertThat.ThrowsWithExceptionMessageContains<InvalidOperationException>( "This method can only be called within the context of an active Web Request.", action); }