/// <summary> /// /// </summary> /// <param name="app"></param> public static void Initialize(IAppBuilder app) { var container = new Container(); container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); SimpleInjectorBootstrap.RegistersDependencies(container); container.RegisterWebApiControllers(GlobalConfiguration.Configuration); ServiceLocator.SetLocatorProvider(() => new SimpleInjectorServiceLocator(container)); var mapper = AutoMapperConfig.CreateMapperConfiguration(); container.RegisterInstance(mapper); container.Register(() => mapper.CreateMapper(container.GetInstance), Lifestyle.Scoped); container.Verify(); GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); app.Use(async(context, next) => { using (AsyncScopedLifestyle.BeginScope(container)) { await next?.Invoke(); } }); }
public void MethodUnGetInstance_SingletonThatIteratesEnumerableInCtorInjectedWithStreamWithScopedInstance_Throws() { // Arrange var container = new Container(); container.Options.EnableAutoVerification = false; container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); container.Collection.Append <ILogger, NullLogger>(Lifestyle.Scoped); container.RegisterSingleton <ILogger, CaptivatingCompositeLogger <IEnumerable <ILogger> > >(); // Act Action action = () => { using (AsyncScopedLifestyle.BeginScope(container)) { // Even though the composite is requested inside an active scope, enumerating the // dependencies inside the constructor should still fail. container.GetInstance <ILogger>(); } }; // Assert AssertThat.ThrowsWithExceptionMessageContains <ActivationException>( "A lifestyle mismatch has been detected.", action); }
public void Configuration(IAppBuilder app) { Container container = new Container(); container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); ContainerConfig.Build(container); HttpConfiguration config = new HttpConfiguration(); container.EnableHttpRequestMessageTracking(config); config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); container.RegisterWebApiControllers(config, AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.StartsWith("OpenSheets."))); BusConfig.Register(container); app.Use(async(context, next) => { using (AsyncScopedLifestyle.BeginScope(container)) { await next(); } }); app.UseWebApi(config); }
public async Task SendEmail(string subject, string content) { using (AsyncScopedLifestyle.BeginScope(container)) { var configuration = container.GetInstance <IConfiguration>(); var employeeRepository = container.GetInstance <IEmployeeRepository>(); var apiKey = configuration.GetSection("SENDGRID_API_KEY").Value; var client = new SendGridClient(apiKey); var from = new EmailAddress("*****@*****.**", "Example User 1"); var employees = await employeeRepository.GetEmployees(); List <EmailAddress> tos = new List <EmailAddress>(); foreach (Employee employee in employees) { var role = await _userManager.GetRolesAsync(employee.User); if (role.FirstOrDefault() == "Manager" || role.FirstOrDefault() == "Finance") { tos.Add(new EmailAddress(employee.User.Email)); } } var htmlContent = content; var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, "", htmlContent); var response = await client.SendEmailAsync(msg); } }
public ISagaQueryScopeContext <TSaga, T> GetQueryScope <T>(SagaQueryConsumeContext <TSaga, T> context) where T : class { if (context.TryGetPayload <Scope>(out var existingScope)) { existingScope.UpdateScope(context); return(new ExistingSagaQueryScopeContext <TSaga, T>(context)); } var scope = AsyncScopedLifestyle.BeginScope(_container); try { scope.UpdateScope(context); var proxy = new SagaQueryConsumeContextProxy <TSaga, T>(context, new PayloadCacheScope(context), context.Query); proxy.UpdatePayload(scope); foreach (Action <ConsumeContext> scopeAction in _scopeActions) { scopeAction(proxy); } return(new CreatedSagaQueryScopeContext <Scope, TSaga, T>(scope, proxy)); } catch { scope.Dispose(); throw; } }
public override async Task <Result> ExecuteAsync <TCommand>(TCommand command) { using (AsyncScopedLifestyle.BeginScope(Container)) { return(await base.ExecuteAsync(command)); } }
private void ConfigureAuth(IAppBuilder app, Container ioCContainer) { using (AsyncScopedLifestyle.BeginScope(ioCContainer)) { var jwtAudience = ConfigurationManager.AppSettings["Jwt:Audience"]; var jwtKey = ConfigurationManager.AppSettings["Jwt:Key"]; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)); var jwtIssuer = ConfigurationManager.AppSettings["Jwt:Issuer"]; var customJwtOAuthBearerAuthenticationProvider = ioCContainer.GetInstance <IOAuthBearerAuthenticationProvider>(); app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions { TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = jwtIssuer, ValidateAudience = true, ValidAudience = jwtAudience, ValidateIssuerSigningKey = true, IssuerSigningKey = key }, Provider = customJwtOAuthBearerAuthenticationProvider }); } }
public void GetCurrentAsyncScopedLifestyle_DisposingTheMiddleScopeBeforeInnerScope_ReturnsOuterScope() { // Arrange var container = new Container(); var lifestyle = new AsyncScopedLifestyle(); var instanceToDispose = new DisposableCommand(); container.Register <DisposableCommand>(lifestyle); using (Scope outerScope = AsyncScopedLifestyle.BeginScope(container)) { Scope middleScope = AsyncScopedLifestyle.BeginScope(container); Scope innerScope = AsyncScopedLifestyle.BeginScope(container); middleScope.Dispose(); innerScope.Dispose(); // Act Scope actualScope = lifestyle.GetCurrentScope(container); // Assert Assert.AreSame(outerScope, actualScope, "Since the middle scope is already disposed, the current scope should be the outer."); } }
public void GetCurrentAsyncScopedLifestyle_DisposingAnInnerScope_ShouldNeverCauseToBeSetToInnerScope() { // Arrange var container = new Container(); container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); var instanceToDispose = new DisposableCommand(); container.Register <DisposableCommand>(Lifestyle.Scoped); using (Scope outerScope = AsyncScopedLifestyle.BeginScope(container)) { Scope outerMiddleScope = AsyncScopedLifestyle.BeginScope(container); Scope innerMiddleScope = AsyncScopedLifestyle.BeginScope(container); Scope innerScope = AsyncScopedLifestyle.BeginScope(container); // This will cause GetCurrentAsyncScopedLifestyle to become outerScope. outerMiddleScope.Dispose(); // This should not cause BeginScope to change innerScope.Dispose(); // Act Scope actualScope = Lifestyle.Scoped.GetCurrentScope(container); // Assert Assert.AreSame(outerScope, actualScope, "Even though the inner middle scope never got disposed, the inner scope should not " + "this scope upon disposal. The outer scope should retain focus."); } }
public SimpleInjectorObjectBuilder(Container parentContainer) { container = parentContainer; externalContainer = true; AsyncScopedLifestyle.BeginScope(container); }
public void GetCurrentAsyncScopedLifestyle_AfterMiddleScopeDisposedWhileInnerScopeNotDisposed_ReturnsOuterScope() { // Arrange var container = new Container(); var lifestyle = new AsyncScopedLifestyle(); var instanceToDispose = new DisposableCommand(); container.Register <DisposableCommand>(lifestyle); using (Scope outerScope = AsyncScopedLifestyle.BeginScope(container)) { Scope middleScope = AsyncScopedLifestyle.BeginScope(container); Scope innerScope = AsyncScopedLifestyle.BeginScope(container); middleScope.Dispose(); // Act Scope actualScope = lifestyle.GetCurrentScope(container); // Assert Assert.AreSame(outerScope, actualScope); } }
public async Task <HealthReport> CheckHealth(CancellationToken ct = default(CancellationToken), Func <HealthCheckRegistration, bool> predicate = null) { predicate = predicate ?? (registration => true); var totalDuration = TimeSpan.Zero; var entries = new Dictionary <string, HealthReportEntry>(); using (var scope = AsyncScopedLifestyle.BeginScope(_container)) { foreach (var registration in _healthCheckRegistrations.Where(predicate)) { ct.ThrowIfCancellationRequested(); using (var cts = CancellationTokenSource.CreateLinkedTokenSource(ct)) { var timeoutTask = GetTimeoutEntry(cts.Token, registration); var checkHealthCoreTask = CheckHealthCore(cts.Token, registration); var entryTask = await Task.WhenAny(timeoutTask, checkHealthCoreTask); var entry = await entryTask; totalDuration += entry.Elapsed; entries[registration.Name] = entry; } } } return(new HealthReport(new ReadOnlyDictionary <string, HealthReportEntry>(entries), totalDuration)); }
public async Task Test() { using (AsyncScopedLifestyle.BeginScope(ContainerFactory.Instance)) { Guid id = Guid.NewGuid(); Create.Command command = new Create.Command { Id = id, Name = "Integration test " + DateTime.UtcNow.Ticks, LecturerName = "Joe Bloggs", NumberOfPlaces = 10 }; await Mediator().Send(command); SignUp.Command signUpCommand = new SignUp.Command { Name = "Terry Student", Age = 21, CourseId = id }; await Mediator().Send(signUpCommand); Assert.True(Notifications().WasReceived <Create.CourseCreated>()); Assert.True(Notifications().WasReceived <SignUp.StudentSignedUp>()); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public async void Configure(IApplicationBuilder app, IWebHostEnvironment env) { DependencyInjection.SimpleInjectorConfiguration.ConfigureApp(app, Configuration, container); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.ConfigureExceptionHandler(container.GetInstance <Application.Logging.ILogger>()); app.UseCors(originPolicy); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); // Seed database using (AsyncScopedLifestyle.BeginScope(container)) { var dispatcher = container.GetInstance <Dispatcher>(); await dispatcher.Dispatch(new SeedUserCommand("admin", "admin")); } }
public ISagaQueryScopeContext <TSaga, T> GetQueryScope <T>(SagaQueryConsumeContext <TSaga, T> context) where T : class { if (context.TryGetPayload <Scope>(out var existingScope)) { return(new ExistingSagaQueryScopeContext <TSaga, T>(context)); } var scope = AsyncScopedLifestyle.BeginScope(_container); try { var proxy = new SagaQueryConsumeContextProxy <TSaga, T>(context, new PayloadCacheScope(context), context.Query); var sagaScope = scope; proxy.GetOrAddPayload(() => sagaScope); return(new CreatedSagaQueryScopeContext <Scope, TSaga, T>(sagaScope, proxy)); } catch { scope.Dispose(); throw; } }
public void Dispose_ObjectRegisteredForDisposalUsingRequestedCurrentLifetimeScope_DisposesThatInstance() { // Arrange var container = new Container(); container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); var instanceToDispose = new DisposableCommand(); container.Register <DisposableCommand>(Lifestyle.Scoped); using (AsyncScopedLifestyle.BeginScope(container)) { var command = container.GetInstance <DisposableCommand>(); command.Disposing += s => { Lifestyle.Scoped.RegisterForDisposal(container, instanceToDispose); }; // Act } // Assert Assert.IsTrue(instanceToDispose.HasBeenDisposed); }
/// <summary> /// https://simpleinjector.readthedocs.io/en/latest/owinintegration.html /// </summary> public static void UseSimpleInjector(this IAppBuilder app, HttpConfiguration config) { var container = new Container(); container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); container.RegisterMediatR(new[] { typeof(Startup).GetTypeInfo().Assembly, // current assembly typeof(AddOperacaoCommand).GetTypeInfo().Assembly, // contracts assembly typeof(ExchangeApplicationSimpleInjectorExtensions).GetTypeInfo().Assembly // application assembly }); container.RegisterExchangeApplication(); container.RegisterWebApiControllers(config); container.Verify(); config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); app.Use(async (context, next) => { using (AsyncScopedLifestyle.BeginScope(container)) { await next(); } }); }
private static async Task Outer(Container container, ICommand command) { DisposableCommand cmd1, cmd2; await Task.Yield(); cmd1 = container.GetInstance <DisposableCommand>(); Assert.AreSame(command, cmd1); using (AsyncScopedLifestyle.BeginScope(container)) { // Act cmd2 = container.GetInstance <DisposableCommand>(); Assert.AreNotSame(command, cmd2); var t1 = Inner(container, cmd2); var t2 = Inner(container, cmd2); await Task.WhenAll(t1, t2).ConfigureAwait(false); Assert.IsFalse(cmd2.HasBeenDisposed); } Assert.IsFalse(cmd1.HasBeenDisposed); Assert.IsTrue(cmd2.HasBeenDisposed); }
public void SetUp() { var assemblies = new[] { typeof(UnitTestSetUp).Assembly }; var container = new Container(); container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); UnitTestSetUp.ConfigureDatabase(container); container.ConfigureMediator(assemblies); Crud.CreateInitializer(container, assemblies) .UseEntityFramework() .Initialize(); container.Options.AllowOverridingRegistrations = true; container.Register <ICrudErrorHandler, TestErrorHandler>(Lifestyle.Singleton); container.Options.AllowOverridingRegistrations = false; _scope = AsyncScopedLifestyle.BeginScope(container); Mediator = _scope.GetInstance <IMediator>(); Context = _scope.GetInstance <DbContext>(); Context.Database.EnsureDeleted(); Container = container; }
public void AsyncScopedLifestyleDispose_WithInstanceExplicitlyRegisteredForDisposal_DisposesThatInstance() { // Arrange var container = ContainerFactory.New(); var scopedLifestyle = new AsyncScopedLifestyle(); // Transient container.Register <DisposableCommand>(); container.RegisterInitializer <DisposableCommand>(instance => { Scope scope = scopedLifestyle.GetCurrentScope(container); // The following line explicitly registers the transient DisposableCommand for disposal when // the execution context scope ends. scope.RegisterForDisposal(instance); }); DisposableCommand command; // Act using (AsyncScopedLifestyle.BeginScope(container)) { command = container.GetInstance <DisposableCommand>(); } // Assert Assert.IsTrue(command.HasBeenDisposed, "The transient instance was expected to be disposed, because it was registered for disposal."); }
public void Consume() { try { var channel = _container.GetInstance <IModel>(); channel.QueueDeclare(queue: "receipt", durable: true, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { using (AsyncScopedLifestyle.BeginScope(_container)) { var json = Encoding.UTF8.GetString(ea.Body); var entity = JsonConvert.DeserializeObject <FinancialEntryEntity>(json); Execute(entity).GetAwaiter().GetResult(); } }; channel.BasicConsume(queue: "receipt", exclusive: false, autoAck: true, consumer: consumer); } catch { throw; } }
public void GetInstance_ResolveMultipleAsyncScopedLifestyledServicesWithStrangeEqualsImplementations_CorrectlyDisposesAllInstances() { // Arrange var container = new Container(); var lifestyle = new AsyncScopedLifestyle(); container.Register <DisposableCommandWithOverriddenEquality1>(lifestyle); container.Register <DisposableCommandWithOverriddenEquality2>(lifestyle); // Act DisposableCommandWithOverriddenEquality1 command1; DisposableCommandWithOverriddenEquality2 command2; // Act using (AsyncScopedLifestyle.BeginScope(container)) { command1 = container.GetInstance <DisposableCommandWithOverriddenEquality1>(); command2 = container.GetInstance <DisposableCommandWithOverriddenEquality2>(); // Give both instances the same hash code. Both have an equals implementation that compared // using the hash code, which make them look like they're the same instance. command1.HashCode = 1; command2.HashCode = 1; } // Assert string assertMessage = "Dispose is expected to be called on this command, even when it contains a GetHashCode and " + "Equals implementation that is totally screwed up, since storing disposable objects, " + "should be completely independent to this implementation. "; Assert.AreEqual(1, command1.DisposeCount, assertMessage + "command1"); Assert.AreEqual(1, command2.DisposeCount, assertMessage + "command2"); }
public ICompensateActivityScopeContext <TActivity, TLog> GetScope(CompensateContext <TLog> context) { if (context.TryGetPayload <Scope>(out var existingContainer)) { var activity = existingContainer .Container .GetInstance <TActivity>(); CompensateActivityContext <TActivity, TLog> activityContext = new HostCompensateActivityContext <TActivity, TLog>(activity, context); return(new ExistingCompensateActivityScopeContext <TActivity, TLog>(activityContext)); } var scope = AsyncScopedLifestyle.BeginScope(_container); try { var activity = scope .Container .GetInstance <TActivity>(); CompensateActivityContext <TActivity, TLog> activityContext = new HostCompensateActivityContext <TActivity, TLog>(activity, context); var contextScope = scope; activityContext.GetOrAddPayload(() => contextScope); return(new CreatedCompensateActivityScopeContext <Scope, TActivity, TLog>(contextScope, activityContext)); } catch { scope.Dispose(); throw; } }
public void AsyncScopedLifestyleDispose_WithWhenScopeEndsRegistration_CallsTheRegisteredAction() { // Arrange int actionCallCount = 0; var container = new Container(); var lifestyle = new AsyncScopedLifestyle(); container.Register <DisposableCommand, DisposableCommand>(lifestyle); container.RegisterInitializer <DisposableCommand>(command => { lifestyle.WhenScopeEnds(container, () => { actionCallCount++; }); }); var scope = AsyncScopedLifestyle.BeginScope(container); try { container.GetInstance <DisposableCommand>(); } finally { // Act scope.Dispose(); } // Assert Assert.AreEqual(1, actionCallCount, "Delegate is expected to be called exactly once."); }
/// <summary> /// 加载Job /// </summary> public static void LoadRecurringTasks() { using (AsyncScopedLifestyle.BeginScope(JobIocConfig.Container)) { var types = from type in Assembly.Load("JuCheap.Services").GetTypes() where type.Namespace?.StartsWith("JuCheap.Services.TaskServices") == true && type.GetInterfaces().Any(t => t == typeof(IRecurringTask)) select type; foreach (var type in types) { var task = JobActivator.Current.ActivateJob(type) as IRecurringTask; if (task == null) { continue; } if (task.Enable) { RecurringJob.AddOrUpdate(task.JobId, () => task.Execute(null), task.CronExpression, timeZone: TimeZoneInfo.Local); } else { RecurringJob.RemoveIfExists(task.JobId); } } } }
public void AsyncScopedLifestyleDispose_WithTransientRegisteredForDisposal_DisposesThatInstance() { // Arrange DisposableCommand transientInstanceToDispose = null; var container = new Container(); container.Options.EnableAutoVerification = false; var lifestyle = new AsyncScopedLifestyle(); container.Register <DisposableCommand>(); container.RegisterInitializer <DisposableCommand>(command => { lifestyle.RegisterForDisposal(container, command); }); var scope = AsyncScopedLifestyle.BeginScope(container); try { transientInstanceToDispose = container.GetInstance <DisposableCommand>(); } finally { // Act scope.Dispose(); } // Assert Assert.IsTrue(transientInstanceToDispose.HasBeenDisposed); }
protected override async Task _runOnce(CancellationToken ctk = default) { using (var scope = AsyncScopedLifestyle.BeginScope(_container)) { await base._runOnce(ctk); } }
public IConsumerScopeContext GetScope(ConsumeContext context) { if (context.TryGetPayload <Scope>(out var existingScope)) { existingScope.UpdateScope(context); return(new ExistingConsumerScopeContext(context)); } var scope = AsyncScopedLifestyle.BeginScope(_container); try { var scopeContext = new ConsumeContextScope(context, scope, scope.Container); scope.UpdateScope(scopeContext); return(new CreatedConsumerScopeContext <Scope>(scope, scopeContext)); } catch { scope.Dispose(); throw; } }
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Acess-Control-Allow-Origin", new[] { "*" }); var user = default(User); try { using (AsyncScopedLifestyle.BeginScope(SimpleInjectorContainer.ContainerInstance)) { var authService = SimpleInjectorContainer.ContainerInstance.GetInstance <IAuthenticationService>(); user = authService.Login(context.UserName, context.Password); } } catch (Exception ex) { context.SetError("invalid_grant", ex.Message); return(Task.FromResult <object>(null)); } var identity = new ClaimsIdentity(context.Options.AuthenticationType); context.Validated(identity); return(Task.FromResult <object>(null)); }
private Task Invoke(Func <Task> method) { using (AsyncScopedLifestyle.BeginScope(_container)) { return(method()); } }