public void Configuration(IAppBuilder app) { var container = new Container(); container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); this.RegisterDependencies(container); container.Verify(); app.Use(async(context, next) => { using (AsyncScopedLifestyle.BeginScope(container)) { await next(); } }); var config = new HttpConfiguration { DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container) }; var jsonFormatter = config.Formatters.JsonFormatter; jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); app.RegisterCors(); // This should happen before call to app.UseWebApi(config); app.UseWebApi(config); config.MapHttpAttributeRoutes(); config.EnsureInitialized(); }
private static void Execute() { string input = COMMAND_REPEAT; while (string.Equals(COMMAND_REPEAT, input, StringComparison.OrdinalIgnoreCase)) { // Business Req: no exceptions try { int numberOfCommands = Get_NumberOfCommands(); (int X, int Y)startCoordinate = Get_StartingCoordinates(); IEnumerable <(DirectionEnum Direction, int Steps)> commands = Get_MoveCommands(numberOfCommands); using (AsyncScopedLifestyle.BeginScope(_container)) { var moveRequest = new MoveRequest(startCoordinate.X, startCoordinate.Y, commands); var useCase = _container.GetInstance <IUseCase <MoveRequest, MoveResponse> >(); var response = useCase.Execute(moveRequest); Console.WriteLine($"Cleaned: {response.CleanedVertices}"); } } finally { Console.WriteLine($"[{COMMAND_REPEAT}]epeat?"); input = Console.ReadLine(); } } }
public void SetUp() { var assemblies = new[] { typeof(UnitTestSetUp).Assembly }; var container = new Container(); container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); Provider = container.AsServiceProvider(); UnitTestSetUp.ConfigureDatabase(container); container.ConfigureAutoMapper(assemblies); Crudless.CreateInitializer(Provider, assemblies) .UseEntityFramework() .Initialize(); container.Options.AllowOverridingRegistrations = true; container.Register <IErrorHandler, 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 async Task <ActionResult <List <string> > > Get(string input, string ctx1, string ctx2) { var resultTasks = new List <Task <string> >(); using (AsyncScopedLifestyle.BeginScope(container)) { var processingService = processingServiceFactory.Create(); var processingContext = processingServiceFactory.GetContext(); processingContext.ContextParameter1 = "some hardcoded 1 v1"; processingContext.ContextParameter2 = "some hardcoded 2 v1"; resultTasks.Add(processingService.Process(input)); } using (AsyncScopedLifestyle.BeginScope(container)) { var processingService = processingServiceFactory.Create(); var processingContext = processingServiceFactory.GetContext(); processingContext.ContextParameter1 = ctx1; processingContext.ContextParameter2 = ctx2; resultTasks.Add(processingService.Process(input)); } using (AsyncScopedLifestyle.BeginScope(container)) { var processingService = processingServiceFactory.Create(); var processingContext = processingServiceFactory.GetContext(); processingContext.ContextParameter1 = "some hardcoded 1 v2"; processingContext.ContextParameter2 = "some hardcoded 2 v2"; resultTasks.Add(processingService.Process(input)); } var result = await Task.WhenAll(resultTasks); return(Ok(result)); }
public void Consume() { try { var channel = _container.GetInstance <IModel>(); channel.QueueDeclare(queue: "conciliate", durable: true, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += async(model, ea) => { using (AsyncScopedLifestyle.BeginScope(_container)) { var json = Encoding.UTF8.GetString(ea.Body); var entity = JsonConvert.DeserializeObject <FinancialEntryEntity>(json); await Execute(entity); } }; channel.BasicConsume(queue: "conciliate", 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 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); }
internal void InitializeContainer(IApplicationBuilder app, ClientAppSettings clientAppSettings, ConnectionstringSettings connectionstringSettings) { var executingAssembly = Assembly.GetExecutingAssembly(); var allAssemblies = new[] { executingAssembly }; // Add application presentation components: _container.RegisterMvcControllers(app); // Register settings as singleton _container.RegisterInstance(clientAppSettings); _container.RegisterInstance(connectionstringSettings); // Add application services. For instance: _container.Register(typeof(IQueryHandler <,>), allAssemblies); _container.Register(typeof(ICommandHandler <>), allAssemblies); _container.Register <HistoricContext>(Lifestyle.Scoped); // Add crosswiring services. // Allow Simple Injector to resolve services from ASP.NET Core. _container.AutoCrossWireAspNetComponents(app); using (AsyncScopedLifestyle.BeginScope(_container)) { var context = _container.GetInstance <HistoricContext>(); context.Database.Migrate(); } _container.Verify(); }
public EnsureExecutionScope(Container container, bool force = false) { if (force || Lifestyle.Scoped.GetCurrentScope(container) == null) { _scope = AsyncScopedLifestyle.BeginScope(container); } }
static void Main(string[] args) { Initialize(); using (AsyncScopedLifestyle.BeginScope(_Container)) { var genero = _Container.GetInstance <IGeneroAppService>(); _Queue = new QueueClient(_CONNECTION_STRING, _NAME_QUEUE); _Queue.RegisterMessageHandler((Microsoft.Azure.ServiceBus.Message M, CancellationToken C) => { string Body = Encoding.UTF8.GetString(M.Body); Console.WriteLine(Body); Genero g = JsonConvert.DeserializeObject <Genero>(Body); genero.Adicionar(g); Console.WriteLine(g); return(Task.CompletedTask); }, new MessageHandlerOptions((E) => { Console.WriteLine(E.Exception.Message); return(Task.CompletedTask); }) { AutoComplete = true, }); while (true) { Thread.Sleep(10000); } } }
/// <summary> /// メッセージの処理を呼び出す /// </summary> /// <param name="messageName">メッセージ名</param> /// <param name="param">コールバックに渡すパラメータ</param> private void Dispatcher(string messageName, object param) { using (AsyncScopedLifestyle.BeginScope(mContainer)) { LinkedList <MessageQueueItem> queue; if (m_MessageQueueList.TryGetValue(messageName, out queue)) { var queueArray = queue.ToArray(); foreach (var queueItem in queueArray) { try { if (string.IsNullOrEmpty(queueItem.ExtentionName)) { var messagecontext = new MessageContext(mContainer, param); queueItem.callback(messagecontext); } else { // 拡張機能に対するメッセージのディスパッチ var messagecontext = new MessageContext(mContainer, queueItem.ExtentionName, param); queueItem.callback(messagecontext); } } catch (Exception expr) { LOG.Error(expr, "拡張機能実行中に処理が停止しました。"); } } } } }
public T Create() { scope = AsyncScopedLifestyle.BeginScope(container); var instance = container.GetInstance <T>(); return(instance); }
public UnitOfWork(Container container, IsolationLevel isolationLevel) { _scope = AsyncScopedLifestyle.BeginScope(container); _dbStore = _scope.GetInstance <IDbStore>(); _session = GetSession(_dbStore); _transaction = _session.BeginTransaction(isolationLevel); }
public async Task ProcessAsync <T>(IMessageStateHandler <T> messageStateHandler, IMessageProcessor next, CancellationToken cancellationToken) where T : class, IMessage { using (AsyncScopedLifestyle.BeginScope(_container)) { await next.ProcessAsync(messageStateHandler, cancellationToken).ConfigureAwait(false); } }
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 IConsumerScopeContext GetScope(ConsumeContext context) { if (context.TryGetPayload <Scope>(out var existingScope)) { existingScope.UpdateScope(context); return(new ExistingConsumerScopeContext(context)); } var scope = AsyncScopedLifestyle.BeginScope(_container); try { scope.UpdateScope(context); var proxy = new ConsumeContextScope(context, scope, scope.Container); return(new CreatedConsumerScopeContext <Scope>(scope, proxy)); } catch { scope.Dispose(); throw; } }
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 Task Handle(T message) { using (AsyncScopedLifestyle.BeginScope(this.container)) { var decoratee = this.decorateeFactory.Invoke(); return(decoratee.Handle(message)); } }
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."); }
protected async Task ExecuteTest(Func <Container, Task> test) { await using (AsyncScopedLifestyle.BeginScope(_container)) { await test(_container); } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var container = new Container(); container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); InitializeContainer(container); container.RegisterWebApiControllers(GlobalConfiguration.Configuration); this.ConfigMediaTypeMappings(GlobalConfiguration.Configuration); container.Verify(); GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); AsyncScopedLifestyle.BeginScope(container); }
public void CanSpecifyScope() { var container = new Container(); container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); container.Register <App>(Lifestyle.Scoped); container.Register <ISomeService, SomeService>(Lifestyle.Scoped); ISomeService svcBeforeRun; using (var scope = AsyncScopedLifestyle.BeginScope(container)) { svcBeforeRun = container.GetInstance <ISomeService>(); } var testOutputs = new AppRunner <App>() .UseSimpleInjector(container, runInScope: ctx => AsyncScopedLifestyle.BeginScope(container)) .RunInMem("Do", _testOutputHelper) .TestOutputs; var services = testOutputs.Get <App.Services>(); services.FromCtor.Should().BeSameAs(services.FromInterceptor); services.FromCtor.Should().NotBeSameAs(svcBeforeRun); }
// ReSharper disable once UnusedMember.Local private void CleanUp() { using (AsyncScopedLifestyle.BeginScope(_container)) { //var configuration = _container.GetInstance<IConfiguration>(); //var discordClient = _container.GetInstance<DiscordSocketClient>(); //var discordGuild = discordClient.GetGuild(configuration.DiscordGuildId) as IGuild; //var channel = discordGuild.GetTextChannelAsync(configuration.DiscordMemberChangeChannelId).Result; //var messages = channel.GetMessagesAsync().Flatten().Result.ToList(); //while (messages.Any()) //{ // channel.DeleteMessagesAsync(messages.Select(m => m.Id)).Wait(); // messages = channel.GetMessagesAsync().Flatten().Result.ToList(); //} using (var repository = _container.GetInstance <Func <IRepository> >().Invoke()) { repository.Players.RemoveRange(repository.Players); repository.Characters.RemoveRange(repository.Characters); repository.Events.RemoveRange(repository.Events); repository.SaveChanges(); } } }
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 override async Task Execute(IJobExecutionContext context) { using (AsyncScopedLifestyle.BeginScope(_container)) { await base.Execute(context).ConfigureAwait(false); } }
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."); } }
/// <summary> /// Resolves all handlers for the given <typeparamref name="TMessage"/> message type /// </summary> public async Task <IEnumerable <IHandleMessages <TMessage> > > GetHandlers <TMessage>(TMessage message, ITransactionContext transactionContext) { var scope = AsyncScopedLifestyle.BeginScope(_container); if (TryGetInstance <IEnumerable <IHandleMessages <TMessage> > >(_container, out var handlerInstances)) { var handlerList = handlerInstances.ToList(); transactionContext.OnDisposed(() => { handlerList .OfType <IDisposable>() .ForEach(disposable => { disposable.Dispose(); }); scope.Dispose(); }); return(handlerList); } scope.Dispose(); return(new IHandleMessages <TMessage> [0]); }
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); }
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 void CanSpecifyScope() { var container = new Container(); container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); container.Register <IoCApp>(Lifestyle.Scoped); container.Register <ISomeIoCService, SomeIoCService>(Lifestyle.Scoped); ISomeIoCService svcBeforeRun; using (var scope = AsyncScopedLifestyle.BeginScope(container)) { svcBeforeRun = container.GetInstance <ISomeIoCService>(); } var result = new AppRunner <IoCApp>() .TrackingInvocations() .UseSimpleInjector(container, runInScope: ctx => AsyncScopedLifestyle.BeginScope(container)) .RunInMem("Do"); var app = result.CommandContext.GetCommandInvocationInfo <IoCApp>().Instance; app.FromCtor.Should().BeSameAs(app.FromInterceptor); app.FromCtor.Should().NotBeSameAs(svcBeforeRun); }