public async Task StartAsync() { Logger.Log(LogLevel.Trace, "Starting CQRS host"); try { if (_lock == null || _disposed) { throw new ObjectDisposedException(nameof(CQRSHost)); } await _lock.WaitAsync(); if (_isStarted) { throw new Exception("Host already started."); } // Dispose the previous connection and operations (if any) DisposeOperations(); DisposeConnection(); // Create a new RabbitMQ connection _connection = _config.CreateConnection(); // Create the service exchange using (var model = _connection.CreateModel()) { model.ExchangeDeclare(ExchangeName, "direct", true, false); } // Create a model, queue, bindings and consumer for each operation var hostOperationGenericType = typeof(HostOperation <,>); var hostOperationSettings = new HostOperationSettings() { Connection = _connection, Serializer = Serializer, Logger = Logger, ServiceName = ServiceName, ExchangeName = ExchangeName }; foreach (var operation in _config.Operations) { Type[] hostOperationTypeArgs = { operation.RequestType, operation.ResponseType }; var hostOperationType = hostOperationGenericType.MakeGenericType(hostOperationTypeArgs); object[] hostOperationParams = { operation, hostOperationSettings }; var hostOperation = (IDisposable)Activator.CreateInstance( hostOperationType, BindingFlags.NonPublic | BindingFlags.Instance, null, hostOperationParams, CultureInfo.InvariantCulture); _operations.Add(hostOperation); } Logger.Log(LogLevel.Trace, "Started CQRS host"); _isStarted = true; } finally { _lock?.Release(); } }