/// <summary> /// Determines whether the command is valid and adds any validation errors to the command's ValidationResults. /// </summary> /// <param name="request">The <see cref="HandlerRequest"/> to be validated.</param> /// <returns>true if command is valid, false otherwise.</returns> public bool Validate(CommandHandlerRequest request) { if (request == null) { throw Error.ArgumentNull("request"); } ModelValidatorProvider[] validatorProviders = request.Configuration.Services.GetModelValidatorProviders(); // Optimization : avoid validating the object graph if there are no validator providers if (validatorProviders.Length == 0) { return true; } ModelMetadataProvider metadataProvider = request.Configuration.Services.GetModelMetadataProvider(); ModelMetadata metadata = metadataProvider.GetMetadataForType(() => request.Command, request.MessageType); ValidationContext validationContext = new ValidationContext { MetadataProvider = metadataProvider, ValidatorProviders = validatorProviders, ValidatorCache = request.Configuration.Services.GetModelValidatorCache(), ModelState = request.ModelState, Visited = new HashSet<object>(ReferenceEqualityComparer.Instance), KeyBuilders = new Stack<IKeyBuilder>(), RootPrefix = string.Empty }; return this.ValidateNodeAndChildren(metadata, validationContext, container: null); }
public void WhenGettingDependencyScopeFromDeepestRequestThenDelegatesToDeepestDependencyResolver() { // Arrange Mock<ICommand> command = new Mock<ICommand>(); HandlerRequest request = new CommandHandlerRequest(this.defaultConfig, command.Object); HandlerRequest innerRequest = new CommandHandlerRequest(this.defaultConfig, command.Object, request); Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>(MockBehavior.Strict); resolver .Setup(r => r.BeginScope()) .Returns(CreateScopeMock); resolver .Setup(r => r.Dispose()); this.defaultConfig.DependencyResolver = resolver.Object; // Act var scope1 = request.GetDependencyScope(); var scope2 = request.GetDependencyScope(false); var scope3 = innerRequest.GetDependencyScope(); var scope4 = innerRequest.GetDependencyScope(false); // Assert Assert.NotNull(scope1); Assert.NotNull(scope2); Assert.NotNull(scope3); Assert.NotNull(scope4); Assert.Same(scope1, scope2); Assert.Same(scope1, scope3); Assert.NotSame(scope1, scope4); resolver.Verify(r => r.BeginScope(), Times.Exactly(2)); }
public void WhenGettingDependencyScopeThenDelegatesToDependencyResolver() { // Arrange Mock<ICommand> command = new Mock<ICommand>(); HandlerRequest request = new CommandHandlerRequest(this.defaultConfig, command.Object); Mock<IDependencyScope> scope = new Mock<IDependencyScope>(MockBehavior.Strict); scope.Setup(s => s.Dispose()); Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>(MockBehavior.Strict); resolver .Setup(r => r.BeginScope()) .Returns(scope.Object); resolver .Setup(r => r.Dispose()); this.defaultConfig.DependencyResolver = resolver.Object; // Act var scope1 = request.GetDependencyScope(); var scope2 = request.GetDependencyScope(); // Assert Assert.NotNull(scope1); Assert.Same(scope1, scope2); resolver.Verify(r => r.BeginScope(), Times.Once()); }
/// <inheritsdoc /> public async Task<HandlerResponse> ExecuteAsync(CommandHandlerRequest request, CancellationToken cancellationToken) { QueuePolicy policy = GetQueuePolicy(request); if (policy == QueuePolicy.NoQueue) { return await this.inner.ExecuteAsync(request, cancellationToken); } return await policy.ExecuteAsync(request, cancellationToken); }
/// <summary>Initializes a new instance of the <see cref="ExceptionResult"/> class.</summary> /// <param name="exception">The exception to include in the error.</param> /// <param name="request">The request message which led to this result.</param> public ExceptionResult(Exception exception, CommandHandlerRequest request) { if (exception == null) { throw new ArgumentNullException("exception"); } this.Exception = exception; this.Request = request; }
private static QueuePolicy GetQueuePolicy(CommandHandlerRequest request) { if (request == null) { throw Error.ArgumentNull("request"); } ServicesContainer servicesContainer = request.Configuration.Services; ICommandHandlerSelector handlerSelector = servicesContainer.GetHandlerSelector(); CommandHandlerDescriptor descriptor = handlerSelector.SelectHandler(request); return descriptor.QueuePolicy; }
public void WhenCreatingHandlerWithoutParametersThenThrowsArgumentNullException() { // Assign ICommandHandlerActivator activator = new DefaultCommandHandlerActivator(); CommandHandlerRequest request = new CommandHandlerRequest(this.config, this.command.Object); CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); // Act // Assert ExceptionAssert.ThrowsArgumentNull(() => activator.Create(null, null), "request"); ExceptionAssert.ThrowsArgumentNull(() => activator.Create(null, descriptor), "request"); ExceptionAssert.ThrowsArgumentNull(() => activator.Create(request, null), "descriptor"); }
public void WhenValidatingInvalidDataAnnotationsValidatableCommandThenReturnsFalse() { // Assign ICommandValidator validator = new DefaultCommandValidator(); ICommand command = new DataAnnotationsValidatableCommand { Property1 = "01234567890123456789" }; CommandHandlerRequest request = new CommandHandlerRequest(this.configuration, command); // Act bool result = validator.Validate(request); // Assert Assert.False(result); Assert.Equal(1, request.ModelState.Count); }
public void WhenValidatingInvalidValidatableObjectCommandThenReturnsFalse() { // Assign ICommandValidator validator = new DefaultCommandValidator(); ICommand command = new ValidatableObjectCommand(false); CommandHandlerRequest request = new CommandHandlerRequest(this.configuration, command); // Act bool result = validator.Validate(request); // Assert Assert.False(result); Assert.Equal(2, request.ModelState.Sum(kvp => kvp.Value.Errors.Count)); }
public void WhenValidatingValidValidatableObjectCommandThenReturnsTrue() { // Assign ICommandValidator validator = new DefaultCommandValidator(); ICommand command = new ValidatableObjectCommand(true); CommandHandlerRequest request = new CommandHandlerRequest(this.configuration, command); // Act bool result = validator.Validate(request); // Assert Assert.True(result); Assert.Equal(0, request.ModelState.Count); }
public void WhenCreatingInstanceThenPropertiesAreDefined() { // Arrange Mock<ICommand> command = new Mock<ICommand>(); // Act CommandHandlerRequest request = new CommandHandlerRequest(this.defaultConfig, command.Object); // Assert Assert.Null(request.ParentRequest); Assert.Same(this.defaultConfig, request.Configuration); Assert.Same(command.Object, request.Command); Assert.Equal(command.Object.GetType(), request.MessageType); Assert.NotEqual(Guid.Empty, request.Id); }
public void WhenExecutingFilterThenCacheIsChecked() { // Arrange CacheAttribute filter = this.CreateAttribute(); SimpleCommand command = new SimpleCommand { Property1 = 12, Property2 = "test" }; CommandHandlerRequest request = new CommandHandlerRequest(this.config, command); CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); CommandHandlerContext context = new CommandHandlerContext(request, descriptor); // Act filter.OnCommandExecuting(context); // Assert this.cache.Verify(c => c.Get(It.IsAny<string>(), It.IsAny<string>()), Times.Once()); Assert.Null(context.Response); }
public void WhenCreatingHandlerFromActivatorThenReturnsHandler() { // Assign ICommandHandlerActivator activator = new DefaultCommandHandlerActivator(); CommandHandlerRequest request = new CommandHandlerRequest(this.config, this.command.Object); CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); this.dependencyResolver.Setup(resolver => resolver.GetService(typeof(SimpleCommandHandler))).Returns(null); // Act ICommandHandler commandHandler = activator.Create(request, descriptor); // Assert Assert.NotNull(commandHandler); Assert.IsType(typeof(SimpleCommandHandler), commandHandler); Assert.Equal(0, descriptor.Properties.Count); this.dependencyResolver.Verify(resolver => resolver.GetService(typeof(SimpleCommandHandler)), Times.Once()); }
public void WhenCreatingInstanceWithParameterCtorThenPropertiesAreDefined() { // Arrange CommandHandlerRequest request = new CommandHandlerRequest(this.config, this.command.Object); CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); // Act CommandHandlerContext context = new CommandHandlerContext(request, descriptor); // Assert Assert.Same(this.config, context.Configuration); Assert.Same(request, context.Request); Assert.Same(request.Command, context.Command); Assert.Same(descriptor, context.Descriptor); Assert.NotNull(context.Request); Assert.NotNull(context.Items); Assert.Equal(0, context.Items.Count); }
public void WhenExecutingFilterToIgnoreThenCacheIsIgnored() { // Arrange CacheAttribute filter = this.CreateAttribute(); SimpleCommand command = new SimpleCommand { Property1 = 12, Property2 = "test" }; SimpleCommand cachedCommand = new SimpleCommand { Property1 = 12, Property2 = "test in cache" }; CommandHandlerRequest request = new CommandHandlerRequest(this.config, command); CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(NotCachedCommand), typeof(NotCachedCommandHandler)); CommandHandlerContext context = new CommandHandlerContext(request, descriptor); this.cache.Setup(c => c.Get(It.IsAny<string>(), It.IsAny<string>())).Returns(new CacheAttribute.CacheEntry(cachedCommand)); // Act filter.OnCommandExecuting(context); // Assert this.cache.Verify(c => c.Get(It.IsAny<string>(), It.IsAny<string>()), Times.Never()); Assert.Null(context.Response); }
/// <summary> /// Initializes a new instance of the <see cref="CommandHandlerContext"/> class. /// </summary> /// <param name="request">The handler request.</param> /// <param name="descriptor">The handler descriptor.</param> public CommandHandlerContext(CommandHandlerRequest request, CommandHandlerDescriptor descriptor) : this() { if (request == null) { throw Error.ArgumentNull("request"); } if (request.Configuration == null) { throw Error.Argument("request"); } this.Configuration = request.Configuration; this.Request = request; this.Command = request.Command; this.Descriptor = descriptor; this.User = this.Configuration.Services.GetPrincipalProvider().Principal; }
/// <summary> /// Execute the request via the worker. /// </summary> /// <param name="request">The <see cref="HandlerRequest"/> to execute.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to cancel the execution.</param> /// <returns>The result of the command, if any.</returns> public Task <HandlerResponse> ExecuteAsync(CommandHandlerRequest request, CancellationToken cancellationToken) { if (request == null) { throw Error.ArgumentNull("request"); } cancellationToken.ThrowIfCancellationRequested(); ServicesContainer servicesContainer = request.Configuration.Services; ICommandHandlerSelector handlerSelector = servicesContainer.GetHandlerSelector(); CommandHandlerDescriptor descriptor = handlerSelector.SelectHandler(request); ICommandHandler commandHandler = descriptor.CreateHandler(request); if (commandHandler == null) { throw CreateHandlerNotFoundException(descriptor); } request.RegisterForDispose(commandHandler, true); CommandHandlerContext context = new CommandHandlerContext(request, descriptor); context.Handler = commandHandler; commandHandler.CommandContext = context; CommandFilterGrouping commandFilterGrouping = descriptor.GetFilterGrouping(); ICommandHandlerResult result = new CommandHandlerFilterResult(context, servicesContainer, commandFilterGrouping.CommandHandlerFilters); if (descriptor.RetryPolicy != RetryPolicy.NoRetry) { result = new RetryHandlerResult(descriptor.RetryPolicy, result); } if (commandFilterGrouping.ExceptionFilters.Length > 0) { IExceptionLogger exceptionLogger = ExceptionServices.GetLogger(servicesContainer); IExceptionHandler exceptionHandler = ExceptionServices.GetHandler(servicesContainer); result = new ExceptionFilterResult(context, commandFilterGrouping.ExceptionFilters, exceptionLogger, exceptionHandler, result); } return(result.ExecuteAsync(cancellationToken)); }
/// <summary> /// Execute the request via the worker. /// </summary> /// <param name="request">The <see cref="HandlerRequest"/> to execute.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to cancel the execution.</param> /// <returns>The result of the command, if any.</returns> public Task<HandlerResponse> ExecuteAsync(CommandHandlerRequest request, CancellationToken cancellationToken) { if (request == null) { throw Error.ArgumentNull("request"); } cancellationToken.ThrowIfCancellationRequested(); ServicesContainer servicesContainer = request.Configuration.Services; ICommandHandlerSelector handlerSelector = servicesContainer.GetHandlerSelector(); CommandHandlerDescriptor descriptor = handlerSelector.SelectHandler(request); ICommandHandler commandHandler = descriptor.CreateHandler(request); if (commandHandler == null) { throw CreateHandlerNotFoundException(descriptor); } request.RegisterForDispose(commandHandler, true); CommandHandlerContext context = new CommandHandlerContext(request, descriptor); context.Handler = commandHandler; commandHandler.CommandContext = context; CommandFilterGrouping commandFilterGrouping = descriptor.GetFilterGrouping(); ICommandHandlerResult result = new CommandHandlerFilterResult(context, servicesContainer, commandFilterGrouping.CommandHandlerFilters); if (descriptor.RetryPolicy != RetryPolicy.NoRetry) { result = new RetryHandlerResult(descriptor.RetryPolicy, result); } if (commandFilterGrouping.ExceptionFilters.Length > 0) { IExceptionLogger exceptionLogger = ExceptionServices.GetLogger(servicesContainer); IExceptionHandler exceptionHandler = ExceptionServices.GetHandler(servicesContainer); result = new ExceptionFilterResult(context, commandFilterGrouping.ExceptionFilters, exceptionLogger, exceptionHandler, result); } return result.ExecuteAsync(cancellationToken); }
/// <summary> /// Selects a <see cref="CommandHandlerDescriptor"/> for the given <see cref="HandlerRequest"/>. /// </summary> /// <param name="request">The request.</param> /// <returns>An <see cref="CommandHandlerDescriptor"/> instance.</returns> public CommandHandlerDescriptor SelectHandler(CommandHandlerRequest request) { if (request == null) { throw Error.ArgumentNull("request"); } CommandHandlerDescriptor result; if (this.handlerInfoCache.Value.TryGetValue(request.MessageType, out result)) { return result; } ICollection<Type> handlerTypes = this.commandHandlerTypeCache.GetHandlerTypes(request.MessageType); if (handlerTypes.Count == 0) { throw Error.InvalidOperation(Resources.DefaultHandlerSelector_HandlerNotFound, request.MessageType.Name); } throw CreateAmbiguousHandlerException(request.MessageType.Name, handlerTypes); }
/// <summary> /// Initializes a new instance of the <see cref="ExceptionContext"/> class using the values provided. /// </summary> /// <param name="exceptionInfo">The exception caught.</param> /// <param name="catchBlock">The catch block where the exception was caught.</param> /// <param name="request">The request being processed when the exception was caught.</param> public ExceptionContext(ExceptionDispatchInfo exceptionInfo, ExceptionContextCatchBlock catchBlock, CommandHandlerRequest request) { if (exceptionInfo == null) { throw new ArgumentNullException("exceptionInfo"); } this.ExceptionInfo = exceptionInfo; if (catchBlock == null) { throw new ArgumentNullException("catchBlock"); } this.CatchBlock = catchBlock; if (request == null) { throw new ArgumentNullException("request"); } this.Request = request; }
/// <summary> /// Selects a <see cref="CommandHandlerDescriptor"/> for the given <see cref="HandlerRequest"/>. /// </summary> /// <param name="request">The request.</param> /// <returns>An <see cref="CommandHandlerDescriptor"/> instance.</returns> public CommandHandlerDescriptor SelectHandler(CommandHandlerRequest request) { if (request == null) { throw Error.ArgumentNull("request"); } CommandHandlerDescriptor result; if (this.handlerInfoCache.Value.TryGetValue(request.MessageType, out result)) { return(result); } ICollection <Type> handlerTypes = this.commandHandlerTypeCache.GetHandlerTypes(request.MessageType); if (handlerTypes.Count == 0) { throw Error.InvalidOperation(Resources.DefaultHandlerSelector_HandlerNotFound, request.MessageType.Name); } throw CreateAmbiguousHandlerException(request.MessageType.Name, handlerTypes); }
public void WhenDisposingScopeFromDeepestRequestThenScopesAreDisposed() { // Arrange Mock<ICommand> command = new Mock<ICommand>(); HandlerRequest request = new CommandHandlerRequest(this.defaultConfig, command.Object); HandlerRequest innerRequest = new CommandHandlerRequest(this.defaultConfig, command.Object, request); Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>(MockBehavior.Strict); int disposedCount = 0; resolver .Setup(r => r.BeginScope()) .Returns(() => CreateVerifiableScopeMock(() => disposedCount++)); resolver .Setup(r => r.Dispose()); this.defaultConfig.DependencyResolver = resolver.Object; request.GetDependencyScope(); innerRequest.GetDependencyScope(false); // Act & Assert Assert.Equal(0, disposedCount); innerRequest.Dispose(); Assert.Equal(1, disposedCount); request.Dispose(); Assert.Equal(2, disposedCount); }
public void WhenValidatingCommandWithUriThenReturnsTrue() { // Assign ICommandValidator validator = new DefaultCommandValidator(); CommandWithUriProperty command = new CommandWithUriProperty(); command.Property1 = new Uri("/test/values", UriKind.Relative); CommandHandlerRequest request = new CommandHandlerRequest(this.configuration, command); // Act bool result = validator.Validate(request); // Assert // A lots of properties of Uri throw exceptions but its still valid Assert.True(result); Assert.Equal(0, request.ModelState.Count); }
public void WhenExecutedFilterVaryByParamsSetIncorrectlyThenCacheIsAlwaysUsed() { // Arrange CacheAttribute filter = this.CreateAttribute(new MemoryCache("test")); filter.Duration = 10; filter.VaryByParams = "XXXX"; CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); SimpleCommand command1 = new SimpleCommand { Property1 = 1, Property2 = "test1" }; CommandHandlerRequest request1 = new CommandHandlerRequest(this.config, command1); CommandHandlerContext context1 = new CommandHandlerContext(request1, descriptor); CommandHandlerExecutedContext executedContext1 = new CommandHandlerExecutedContext(context1, null); executedContext1.SetResponse("result1"); SimpleCommand command2 = new SimpleCommand { Property1 = 2, Property2 = "test2" }; CommandHandlerRequest request2 = new CommandHandlerRequest(this.config, command2); CommandHandlerContext context2 = new CommandHandlerContext(request2, descriptor); CommandHandlerExecutedContext executedContext2 = new CommandHandlerExecutedContext(context2, null); executedContext2.SetResponse( "result2"); SimpleCommand command3 = new SimpleCommand { Property1 = 2, Property2 = "test3" }; CommandHandlerRequest request3 = new CommandHandlerRequest(this.config, command3); CommandHandlerContext context3 = new CommandHandlerContext(request3, descriptor); CommandHandlerExecutedContext executedContext3 = new CommandHandlerExecutedContext(context3, null); executedContext3.SetResponse("result3"); // Act filter.OnCommandExecuting(context1); filter.OnCommandExecuted(executedContext1); filter.OnCommandExecuting(context2); filter.OnCommandExecuted(executedContext2); filter.OnCommandExecuting(context3); filter.OnCommandExecuted(executedContext3); // Assert Assert.Equal("result1", executedContext1.Response.Value); Assert.Equal("result1", executedContext2.Response.Value); Assert.Equal("result1", executedContext3.Response.Value); }
public void WhenExecutedFilterVaryByUserThenCacheIsUpdated() { // Arrange CacheAttribute filter = this.CreateAttribute(new MemoryCache("test")); filter.Duration = 10; filter.VaryByUser = true; filter.VaryByParams = CacheAttribute.VaryByParamsNone; CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); SimpleCommand command1 = new SimpleCommand { Property1 = 1, Property2 = "test1" }; CommandHandlerRequest request1 = new CommandHandlerRequest(this.config, command1); CommandHandlerContext context1 = new CommandHandlerContext(request1, descriptor); context1.User = new GenericPrincipal(new GenericIdentity("user1"), null); CommandHandlerExecutedContext executedContext1 = new CommandHandlerExecutedContext(context1, null); executedContext1.Response = new HandlerResponse(request1, "result1"); SimpleCommand command2 = new SimpleCommand { Property1 = 1, Property2 = "test1" }; CommandHandlerRequest request2 = new CommandHandlerRequest(this.config, command2); CommandHandlerContext context2 = new CommandHandlerContext(request2, descriptor); context2.User = new GenericPrincipal(new GenericIdentity("user2"), null); CommandHandlerExecutedContext executedContext2 = new CommandHandlerExecutedContext(context2, null); executedContext2.Response = new HandlerResponse(request2, "result2"); SimpleCommand command3 = new SimpleCommand { Property1 = 1, Property2 = "test1" }; CommandHandlerRequest request3 = new CommandHandlerRequest(this.config, command3); CommandHandlerContext context3 = new CommandHandlerContext(request3, descriptor); context3.User = new GenericPrincipal(new GenericIdentity("user1"), null); CommandHandlerExecutedContext executedContext3 = new CommandHandlerExecutedContext(context3, null); executedContext3.Response = new HandlerResponse(request3, "result3"); // Act filter.OnCommandExecuting(context1); filter.OnCommandExecuted(executedContext1); filter.OnCommandExecuting(context2); filter.OnCommandExecuted(executedContext2); filter.OnCommandExecuting(context3); filter.OnCommandExecuted(executedContext3); // Assert Assert.Equal("result1", executedContext1.Response.Value); Assert.Equal("result2", executedContext2.Response.Value); Assert.Equal("result1", executedContext3.Response.Value); }
public void WhenValidatingInvalidMixedValidatableCommandThenReturnsFalse() { // Assign ICommandValidator validator = new DefaultCommandValidator(); MixedValidatableCommand command = new MixedValidatableCommand(false); command.Property1 = "123456789456132456"; CommandHandlerRequest request = new CommandHandlerRequest(this.configuration, command); // Act bool result = validator.Validate(request); // Assert Assert.False(result); // Validator ignore IValidatableObject validation until DataAnnotations succeed. Assert.Equal(1, request.ModelState.Count); }
public void CreateTranscientHandler_InstancianteEachTime() { // Arrange var config = new ProcessorConfiguration(); config.DefaultHandlerLifetime = HandlerLifetime.Transient; ICommandHandlerActivator activator = new DefaultCommandHandlerActivator(); CommandHandlerRequest request1 = new CommandHandlerRequest(config, this.command.Object); CommandHandlerRequest request2 = new CommandHandlerRequest(config, this.command.Object); CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); CommandHandlerDescriptor descriptor2 = new CommandHandlerDescriptor(config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); // Act var handler1 = activator.Create(request1, descriptor); var handler2 = activator.Create(request1, descriptor); var handler3 = activator.Create(request2, descriptor); var handler4 = activator.Create(request1, descriptor2); // Assert Assert.NotNull(handler1); Assert.NotNull(handler2); Assert.NotNull(handler3); Assert.NotNull(handler4); Assert.NotSame(handler1, handler2); Assert.NotSame(handler1, handler3); Assert.NotSame(handler1, handler4); Assert.NotSame(handler2, handler3); Assert.NotSame(handler2, handler4); Assert.NotSame(handler3, handler4); }
public void WhenExecutedFilterWithExceptionThenCacheIsNotUpdated() { // Arrange CacheAttribute filter = this.CreateAttribute(); SimpleCommand command = new SimpleCommand { Property1 = 12, Property2 = "test" }; CommandHandlerRequest request = new CommandHandlerRequest(this.config, command); CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); CommandHandlerContext context = new CommandHandlerContext(request, descriptor); Exception exception = new Exception(); ExceptionDispatchInfo exceptionInfo = ExceptionDispatchInfo.Capture(exception); CommandHandlerExecutedContext executedContext = new CommandHandlerExecutedContext(context, exceptionInfo); // Act filter.OnCommandExecuted(executedContext); // Assert this.cache.Verify(c => c.Add(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<DateTimeOffset>(), It.IsAny<string>()), Times.Never()); Assert.Null(context.Response); }
public void WhenCreatingHandlerThrowExceptionThenRethowsInvalidOperationException() { // Arrange ICommandHandlerActivator activator = new DefaultCommandHandlerActivator(); CommandHandlerRequest request = new CommandHandlerRequest(this.config, this.command.Object); CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); this.dependencyResolver .Setup(resolver => resolver.GetService(typeof(SimpleCommandHandler))) .Throws<CommandHandlerNotFoundException>(); bool exceptionRaised = false; // Act try { activator.Create(request, descriptor); } catch (InvalidOperationException) { exceptionRaised = true; } // Assert Assert.True(exceptionRaised); }
public void WhenCreatingHandlerFromTwoDescriptorsAndDependencyResolverThenGetActivatorDepencyResolver() { // Assign ICommandHandlerActivator activator = new DefaultCommandHandlerActivator(); CommandHandlerRequest request = new CommandHandlerRequest(this.config, this.command.Object); CommandHandlerDescriptor descriptor1 = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); CommandHandlerDescriptor descriptor2 = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); int[] i = { 0 }; this.dependencyResolver .When(() => i[0] < 1) .Setup(resolver => resolver.GetService(typeof(SimpleCommandHandler))) .Returns(null) .Callback(() => i[0]++); this.dependencyResolver .When(() => i[0] >= 1) .Setup(resolver => resolver.GetService(typeof(SimpleCommandHandler))) .Returns(new SimpleCommandHandler()); // Act activator.Create(request, descriptor1); ICommandHandler commandHandler = activator.Create(request, descriptor2); // Assert Assert.NotNull(commandHandler); Assert.IsType(typeof(SimpleCommandHandler), commandHandler); Assert.Equal(0, descriptor2.Properties.Count); this.dependencyResolver.Verify(resolver => resolver.GetService(typeof(SimpleCommandHandler)), Times.Exactly(2)); }
public void WhenCreatingHandlerFromTwoDescriptorsThenGetActivatorFromProperties() { // Assign ICommandHandlerActivator activator = new DefaultCommandHandlerActivator(); CommandHandlerRequest request1 = new CommandHandlerRequest(this.config, this.command.Object); CommandHandlerRequest request2 = new CommandHandlerRequest(this.config, this.command.Object); CommandHandlerDescriptor descriptor1 = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); CommandHandlerDescriptor descriptor2 = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); this.dependencyResolver.Setup(resolver => resolver.GetService(typeof(SimpleCommandHandler))).Returns(null); // Act activator.Create(request1, descriptor1); activator.Create(request2, descriptor2); ICommandHandler commandHandler = activator.Create(request2, descriptor2); // Assert Assert.NotNull(commandHandler); Assert.IsType(typeof(SimpleCommandHandler), commandHandler); Assert.Equal(1, descriptor2.Properties.Count); this.dependencyResolver.Verify(resolver => resolver.GetService(typeof(SimpleCommandHandler)), Times.Exactly(2)); }
public void WhenDisposingThenScopeIsDisposed() { // Arrange Mock<ICommand> command = new Mock<ICommand>(); HandlerRequest request = new CommandHandlerRequest(this.defaultConfig, command.Object); Mock<IDependencyScope> scope = new Mock<IDependencyScope>(MockBehavior.Strict); scope.Setup(s => s.Dispose()); Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>(MockBehavior.Strict); resolver .Setup(r => r.BeginScope()) .Returns(scope.Object); resolver .Setup(r => r.Dispose()); this.defaultConfig.DependencyResolver = resolver.Object; request.GetDependencyScope(); // Act request.Dispose(); // Assert scope.Verify(s => s.Dispose(), Times.Once()); }
/// <summary> /// Creates a handler instance for the given <see cref="HandlerRequest"/>. /// </summary> /// <param name="request">The request.</param> /// <returns>The created handler instance.</returns> public virtual ICommandHandler CreateHandler(CommandHandlerRequest request) { return(this.handlerActivator.Create(request, this)); }