├── AspNetCore.EventBus ├── IDynamicEventHandler.cs ├── IEventHandler.cs ├── RabbitMQ │ ├── IRabbitMQPersistentConnection.cs │ ├── EventBusRabbitMQOptions.cs │ ├── EventBusRabbitMQExtentions.cs │ ├── DefaultRabbitMQPersistentConnection.cs │ └── EventBusRabbitMQ.cs ├── Event.cs ├── EventBusExtentions.cs ├── IEventBus.cs ├── AspNetCore.EventBus.csproj ├── SubscriptionInfo.cs ├── GenericTypeExtensions.cs ├── IEventBusSubscriptionsManager.cs └── EventBusSubscriptionsManager.cs ├── AspNetCore.EventBus.sln ├── README.md └── .gitignore /AspNetCore.EventBus/IDynamicEventHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace AspNetCore.EventBus 4 | { 5 | public interface IDynamicEventHandler 6 | { 7 | Task Handle(dynamic eventData); 8 | } 9 | } -------------------------------------------------------------------------------- /AspNetCore.EventBus/IEventHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace AspNetCore.EventBus 4 | { 5 | public interface IEventHandler where TEvent : Event 6 | { 7 | Task Handle(TEvent @event); 8 | } 9 | } -------------------------------------------------------------------------------- /AspNetCore.EventBus/RabbitMQ/IRabbitMQPersistentConnection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using RabbitMQ.Client; 3 | 4 | namespace AspNetCore.EventBus.RabbitMQ 5 | { 6 | public interface IRabbitMQPersistentConnection : IDisposable 7 | { 8 | bool IsConnected { get; } 9 | 10 | bool TryConnect(); 11 | 12 | IModel CreateModel(); 13 | } 14 | } -------------------------------------------------------------------------------- /AspNetCore.EventBus/Event.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace AspNetCore.EventBus 4 | { 5 | public class Event 6 | { 7 | public Guid Id { get; } 8 | 9 | public DateTime CreationDate { get; } 10 | 11 | public Event() 12 | { 13 | Id = Guid.NewGuid(); 14 | CreationDate = DateTime.UtcNow; 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /AspNetCore.EventBus/EventBusExtentions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace AspNetCore.EventBus 4 | { 5 | public static class EventBusExtentions 6 | { 7 | public static void AddEventBus(this IServiceCollection services) where TEventBus : class, IEventBus 8 | { 9 | services.AddSingleton(); 10 | 11 | services.AddSingleton(); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /AspNetCore.EventBus/IEventBus.cs: -------------------------------------------------------------------------------- 1 | namespace AspNetCore.EventBus 2 | { 3 | public interface IEventBus 4 | { 5 | void Publish(Event @event); 6 | 7 | void Subscribe() where T : Event where TH : IEventHandler; 8 | 9 | void Unsubscribe() where TH : IEventHandler where T : Event; 10 | 11 | void SubscribeDynamic(string eventName) where TH : IDynamicEventHandler; 12 | 13 | void UnsubscribeDynamic(string eventName) where TH : IDynamicEventHandler; 14 | } 15 | } -------------------------------------------------------------------------------- /AspNetCore.EventBus/RabbitMQ/EventBusRabbitMQOptions.cs: -------------------------------------------------------------------------------- 1 | namespace AspNetCore.EventBus.RabbitMQ 2 | { 3 | public class EventBusRabbitMQOptions 4 | { 5 | public string HostName { get; set; } 6 | 7 | public string UserName { get; set; } 8 | 9 | public string Password { get; set; } 10 | 11 | public string QueueName { get; set; } = "event_bus_queue"; 12 | 13 | public string BrokerName { get; set; } = "event_bus"; 14 | 15 | public int RetryCount { get; set; } = 5; 16 | } 17 | } -------------------------------------------------------------------------------- /AspNetCore.EventBus/AspNetCore.EventBus.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /AspNetCore.EventBus/RabbitMQ/EventBusRabbitMQExtentions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Extensions.DependencyInjection; 3 | 4 | namespace AspNetCore.EventBus.RabbitMQ 5 | { 6 | public static class EventBusRabbitMQExtentions 7 | { 8 | public static void AddEventBusRabbitMQ(this IServiceCollection services, Action configureOptions) 9 | { 10 | var options = new EventBusRabbitMQOptions(); 11 | 12 | configureOptions(options); 13 | 14 | services.Configure(configureOptions); 15 | 16 | services.AddSingleton(); 17 | 18 | services.AddEventBus(); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /AspNetCore.EventBus/SubscriptionInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace AspNetCore.EventBus 4 | { 5 | public class SubscriptionInfo 6 | { 7 | public bool IsDynamic { get; } 8 | 9 | public Type HandlerType { get; } 10 | 11 | private SubscriptionInfo(bool isDynamic, Type handlerType) 12 | { 13 | IsDynamic = isDynamic; 14 | 15 | HandlerType = handlerType; 16 | } 17 | 18 | public static SubscriptionInfo Dynamic(Type handlerType) 19 | { 20 | return new SubscriptionInfo(true, handlerType); 21 | } 22 | 23 | public static SubscriptionInfo Typed(Type handlerType) 24 | { 25 | return new SubscriptionInfo(false, handlerType); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /AspNetCore.EventBus.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspNetCore.EventBus", "AspNetCore.EventBus\AspNetCore.EventBus.csproj", "{AC8D3BA6-ED74-40C3-BAAF-DD31337B2EEF}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|Any CPU = Debug|Any CPU 9 | Release|Any CPU = Release|Any CPU 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {AC8D3BA6-ED74-40C3-BAAF-DD31337B2EEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 13 | {AC8D3BA6-ED74-40C3-BAAF-DD31337B2EEF}.Debug|Any CPU.Build.0 = Debug|Any CPU 14 | {AC8D3BA6-ED74-40C3-BAAF-DD31337B2EEF}.Release|Any CPU.ActiveCfg = Release|Any CPU 15 | {AC8D3BA6-ED74-40C3-BAAF-DD31337B2EEF}.Release|Any CPU.Build.0 = Release|Any CPU 16 | EndGlobalSection 17 | EndGlobal 18 | -------------------------------------------------------------------------------- /AspNetCore.EventBus/GenericTypeExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | namespace AspNetCore.EventBus 5 | { 6 | public static class GenericTypeExtensions 7 | { 8 | public static string GetGenericTypeName(this Type type) 9 | { 10 | string typeName; 11 | 12 | if (type.IsGenericType) 13 | { 14 | var genericTypes = string.Join(",", type.GetGenericArguments().Select(t => t.Name).ToArray()); 15 | 16 | typeName = $"{type.Name.Remove(type.Name.IndexOf('`'))}<{genericTypes}>"; 17 | } 18 | else 19 | { 20 | typeName = type.Name; 21 | } 22 | 23 | return typeName; 24 | } 25 | 26 | public static string GetGenericTypeName(this object @object) 27 | { 28 | return @object.GetType().GetGenericTypeName(); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /AspNetCore.EventBus/IEventBusSubscriptionsManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace AspNetCore.EventBus 5 | { 6 | public interface IEventBusSubscriptionsManager 7 | { 8 | bool IsEmpty { get; } 9 | 10 | event EventHandler OnEventRemoved; 11 | 12 | void AddDynamicSubscription(string eventName) where TH : IDynamicEventHandler; 13 | 14 | void AddSubscription() where T : Event where TH : IEventHandler; 15 | 16 | void RemoveSubscription() where TH : IEventHandler where T : Event; 17 | 18 | void RemoveDynamicSubscription(string eventName) where TH : IDynamicEventHandler; 19 | 20 | bool HasSubscriptionsForEvent() where T : Event; 21 | 22 | bool HasSubscriptionsForEvent(string eventName); 23 | 24 | Type GetEventTypeByName(string eventName); 25 | 26 | void Clear(); 27 | 28 | IEnumerable GetHandlersForEvent() where T : Event; 29 | 30 | IEnumerable GetHandlersForEvent(string eventName); 31 | 32 | string GetEventKey(); 33 | } 34 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AspNetCore.EventBus.RabbitMQ 2 | An EventBus base on Asp.net core 3.1 and RabbitMQ. 3 | 4 | Made by inspiration from [dotnet-architecture/eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers), however there are some changes: 5 | - Replace Autofac with default asp.net core ioc container. 6 | - Add some extention methods for adding event bus. 7 | - Delayed to create rabbitmq channel for event publish. 8 | - Class name changed. 9 | 10 | ## Add RabbitMQ EventBus 11 | 12 | ```csharp 13 | public void ConfigureServices(IServiceCollection services) 14 | { 15 | ... 16 | services.AddEventBusRabbitMQ(o => 17 | { 18 | o.HostName = "localhost"; 19 | o.UserName = "guest"; 20 | o.Password = "guest"; 21 | o.QueueName = "event_bus_queue"; 22 | o.BrokerName = "event_bus"; 23 | o.RetryCount = 5; 24 | }); 25 | } 26 | ``` 27 | 28 | ## Add Custom EventBus 29 | 30 | ```csharp 31 | public void ConfigureServices(IServiceCollection services) 32 | { 33 | ... 34 | services.AddEventBus(); 35 | } 36 | ``` 37 | 38 | **!important: You must Add any LoggerProvider** 39 | 40 | ## Publish 41 | 42 | ```csharp 43 | public class UserRegisterEvent : Event 44 | { 45 | public string Name { get; set; } 46 | } 47 | 48 | public class ValuesController : ControllerBase 49 | { 50 | private readonly IEventBus _eventBus; 51 | 52 | public ValuesController(IEventBus eventBus) 53 | { 54 | _eventBus = eventBus; 55 | } 56 | 57 | [HttpPost] 58 | public ActionResult Post() 59 | { 60 | _eventBus.Publish(new UserRegisterEvent() { Name = "Fatih" }); 61 | return Ok(); 62 | } 63 | } 64 | ``` 65 | 66 | ## Subscribe 67 | 68 | ```csharp 69 | public class UserRegisterEventHandler : IEventHandler 70 | { 71 | private readonly ILogger _logger; 72 | 73 | public UserRegisterEventHandler(ILogger logger) 74 | { 75 | _logger = logger; 76 | } 77 | 78 | public Task Handle(UserRegisterEvent @event) 79 | { 80 | _logger.LogInformation($"Welcome {@event.Name}!"); 81 | return Task.FromResult(0); 82 | } 83 | } 84 | ``` 85 | 86 | ```csharp 87 | public void ConfigureServices(IServiceCollection services) 88 | { 89 | services.AddTransient(); 90 | ... 91 | } 92 | ``` 93 | 94 | ```csharp 95 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 96 | { 97 | var eventBus = app.ApplicationServices.GetRequiredService(); 98 | eventBus.Subscribe(); 99 | ... 100 | } 101 | ``` 102 | 103 | 104 | 105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /AspNetCore.EventBus/RabbitMQ/DefaultRabbitMQPersistentConnection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Net.Sockets; 4 | using Microsoft.Extensions.Logging; 5 | using Microsoft.Extensions.Options; 6 | using Polly; 7 | using RabbitMQ.Client; 8 | using RabbitMQ.Client.Events; 9 | using RabbitMQ.Client.Exceptions; 10 | 11 | namespace AspNetCore.EventBus.RabbitMQ 12 | { 13 | public class DefaultRabbitMQPersistentConnection : IRabbitMQPersistentConnection 14 | { 15 | private readonly IConnectionFactory _connectionFactory; 16 | 17 | private readonly ILogger _logger; 18 | 19 | private readonly int _retryCount; 20 | 21 | private IConnection _connection; 22 | 23 | private bool _disposed; 24 | 25 | private readonly object _syncRoot = new object(); 26 | 27 | public DefaultRabbitMQPersistentConnection( 28 | IOptionsMonitor options, 29 | ILogger logger) 30 | { 31 | _logger = logger; 32 | 33 | _connectionFactory = new ConnectionFactory() 34 | { 35 | HostName = options.CurrentValue.HostName, 36 | UserName = options.CurrentValue.UserName, 37 | Password = options.CurrentValue.Password 38 | }; 39 | 40 | _retryCount = options.CurrentValue.RetryCount; 41 | } 42 | 43 | public bool IsConnected => _connection != null && _connection.IsOpen && !_disposed; 44 | 45 | public IModel CreateModel() 46 | { 47 | if (!IsConnected) 48 | { 49 | throw new InvalidOperationException("No RabbitMQ connections are available to perform this action"); 50 | } 51 | 52 | return _connection.CreateModel(); 53 | } 54 | 55 | public void Dispose() 56 | { 57 | if (_disposed) return; 58 | 59 | _disposed = true; 60 | 61 | try 62 | { 63 | _connection?.Dispose(); 64 | } 65 | catch (IOException ex) 66 | { 67 | _logger.LogCritical(ex.ToString()); 68 | } 69 | } 70 | 71 | public bool TryConnect() 72 | { 73 | _logger.LogInformation("RabbitMQ Client is trying to connect"); 74 | 75 | lock (_syncRoot) 76 | { 77 | if (IsConnected) 78 | { 79 | return true; 80 | } 81 | 82 | var policy = Policy.Handle().Or() 83 | .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) => 84 | { 85 | _logger.LogWarning(ex, "RabbitMQ Client could not connect after {TimeOut}s ({ExceptionMessage})", 86 | $"{time.TotalSeconds:n1}", ex.Message); 87 | } 88 | ); 89 | 90 | policy.Execute(() => { _connection = _connectionFactory.CreateConnection(); }); 91 | 92 | if (IsConnected) 93 | { 94 | _connection.ConnectionShutdown += OnConnectionShutdown; 95 | 96 | _connection.CallbackException += OnCallbackException; 97 | 98 | _connection.ConnectionBlocked += OnConnectionBlocked; 99 | 100 | _logger.LogInformation("RabbitMQ acquired a persistent connection to '{HostName}' and is subscribed to failure events", 101 | _connection.Endpoint.HostName); 102 | 103 | return true; 104 | } 105 | 106 | _logger.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened"); 107 | 108 | return false; 109 | } 110 | } 111 | 112 | private void OnConnectionBlocked(object sender, ConnectionBlockedEventArgs e) 113 | { 114 | if (_disposed) return; 115 | 116 | _logger.LogWarning("A RabbitMQ connection is shutdown. Trying to re-connect..."); 117 | 118 | TryConnect(); 119 | } 120 | 121 | private void OnCallbackException(object sender, CallbackExceptionEventArgs e) 122 | { 123 | if (_disposed) return; 124 | 125 | _logger.LogWarning("A RabbitMQ connection throw exception. Trying to re-connect..."); 126 | 127 | TryConnect(); 128 | } 129 | 130 | private void OnConnectionShutdown(object sender, ShutdownEventArgs reason) 131 | { 132 | if (_disposed) return; 133 | 134 | _logger.LogWarning("A RabbitMQ connection is on shutdown. Trying to re-connect..."); 135 | 136 | TryConnect(); 137 | } 138 | } 139 | } -------------------------------------------------------------------------------- /AspNetCore.EventBus/EventBusSubscriptionsManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace AspNetCore.EventBus 6 | { 7 | public class EventBusSubscriptionsManager : IEventBusSubscriptionsManager 8 | { 9 | private readonly Dictionary> _handlers; 10 | 11 | private readonly Dictionary _eventTypes; 12 | 13 | public event EventHandler OnEventRemoved; 14 | 15 | public EventBusSubscriptionsManager() 16 | { 17 | _handlers = new Dictionary>(); 18 | 19 | _eventTypes = new Dictionary(); 20 | } 21 | 22 | public bool IsEmpty => !_handlers.Keys.Any(); 23 | 24 | public void Clear() => _handlers.Clear(); 25 | 26 | public void AddDynamicSubscription(string eventName) where TH : IDynamicEventHandler 27 | { 28 | DoAddSubscription(typeof(TH), eventName, true); 29 | } 30 | 31 | public void AddSubscription() where T : Event where TH : IEventHandler 32 | { 33 | var eventName = GetEventKey(); 34 | 35 | DoAddSubscription(typeof(TH), eventName, false); 36 | 37 | _eventTypes.Add(eventName, typeof(T)); 38 | } 39 | 40 | private void DoAddSubscription(Type handlerType, string eventName, bool isDynamic) 41 | { 42 | if (!HasSubscriptionsForEvent(eventName)) 43 | { 44 | _handlers.Add(eventName, new List()); 45 | } 46 | 47 | if (_handlers[eventName].Any(s => s.HandlerType == handlerType)) 48 | { 49 | throw new ArgumentException($"Handler Type {handlerType.Name} already registered for '{eventName}'", nameof(handlerType)); 50 | } 51 | 52 | _handlers[eventName].Add(isDynamic ? SubscriptionInfo.Dynamic(handlerType) : SubscriptionInfo.Typed(handlerType)); 53 | } 54 | 55 | public void RemoveDynamicSubscription(string eventName) where TH : IDynamicEventHandler 56 | { 57 | var handlerToRemove = FindDynamicSubscriptionToRemove(eventName); 58 | 59 | DoRemoveHandler(eventName, handlerToRemove); 60 | } 61 | 62 | public void RemoveSubscription() where TH : IEventHandler where T : Event 63 | { 64 | var handlerToRemove = FindSubscriptionToRemove(); 65 | 66 | var eventName = GetEventKey(); 67 | 68 | DoRemoveHandler(eventName, handlerToRemove); 69 | } 70 | 71 | private void DoRemoveHandler(string eventName, SubscriptionInfo subsToRemove) 72 | { 73 | if (subsToRemove != null) 74 | { 75 | _handlers[eventName].Remove(subsToRemove); 76 | 77 | if (!_handlers[eventName].Any()) 78 | { 79 | _handlers.Remove(eventName); 80 | 81 | if (_eventTypes.ContainsKey(eventName)) 82 | { 83 | _eventTypes.Remove(eventName); 84 | } 85 | 86 | RaiseOnEventRemoved(eventName); 87 | } 88 | } 89 | } 90 | 91 | public IEnumerable GetHandlersForEvent() where T : Event 92 | { 93 | var key = GetEventKey(); 94 | 95 | return GetHandlersForEvent(key); 96 | } 97 | 98 | public IEnumerable GetHandlersForEvent(string eventName) => _handlers[eventName]; 99 | 100 | private void RaiseOnEventRemoved(string eventName) 101 | { 102 | OnEventRemoved?.Invoke(this, eventName); 103 | } 104 | 105 | private SubscriptionInfo FindDynamicSubscriptionToRemove(string eventName) where TH : IDynamicEventHandler 106 | { 107 | return DoFindSubscriptionToRemove(eventName, typeof(TH)); 108 | } 109 | 110 | private SubscriptionInfo FindSubscriptionToRemove() where T : Event where TH : IEventHandler 111 | { 112 | var eventName = GetEventKey(); 113 | 114 | return DoFindSubscriptionToRemove(eventName, typeof(TH)); 115 | } 116 | 117 | private SubscriptionInfo DoFindSubscriptionToRemove(string eventName, Type handlerType) 118 | { 119 | if (!HasSubscriptionsForEvent(eventName)) 120 | { 121 | return null; 122 | } 123 | 124 | return _handlers[eventName].SingleOrDefault(s => s.HandlerType == handlerType); 125 | } 126 | 127 | public bool HasSubscriptionsForEvent() where T : Event 128 | { 129 | var key = GetEventKey(); 130 | 131 | return HasSubscriptionsForEvent(key); 132 | } 133 | 134 | public bool HasSubscriptionsForEvent(string eventName) => _handlers.ContainsKey(eventName); 135 | 136 | public Type GetEventTypeByName(string eventName) => _eventTypes[eventName]; 137 | 138 | public string GetEventKey() 139 | { 140 | return typeof(T).Name; 141 | } 142 | } 143 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # globs 2 | Makefile.in 3 | *.userprefs 4 | *.usertasks 5 | config.make 6 | config.status 7 | aclocal.m4 8 | install-sh 9 | autom4te.cache/ 10 | *.tar.gz 11 | tarballs/ 12 | test-results/ 13 | 14 | # Mac bundle stuff 15 | *.dmg 16 | *.app 17 | 18 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 19 | # General 20 | .DS_Store 21 | .AppleDouble 22 | .LSOverride 23 | 24 | # Icon must end with two \r 25 | Icon 26 | 27 | 28 | # Thumbnails 29 | ._* 30 | 31 | # Files that might appear in the root of a volume 32 | .DocumentRevisions-V100 33 | .fseventsd 34 | .Spotlight-V100 35 | .TemporaryItems 36 | .Trashes 37 | .VolumeIcon.icns 38 | .com.apple.timemachine.donotpresent 39 | 40 | # Directories potentially created on remote AFP share 41 | .AppleDB 42 | .AppleDesktop 43 | Network Trash Folder 44 | Temporary Items 45 | .apdisk 46 | 47 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 48 | # Windows thumbnail cache files 49 | Thumbs.db 50 | ehthumbs.db 51 | ehthumbs_vista.db 52 | 53 | # Dump file 54 | *.stackdump 55 | 56 | # Folder config file 57 | [Dd]esktop.ini 58 | 59 | # Recycle Bin used on file shares 60 | $RECYCLE.BIN/ 61 | 62 | # Windows Installer files 63 | *.cab 64 | *.msi 65 | *.msix 66 | *.msm 67 | *.msp 68 | 69 | # Windows shortcuts 70 | *.lnk 71 | 72 | # content below from: https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 73 | ## Ignore Visual Studio temporary files, build results, and 74 | ## files generated by popular Visual Studio add-ons. 75 | ## 76 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 77 | 78 | # User-specific files 79 | *.suo 80 | *.user 81 | *.userosscache 82 | *.sln.docstates 83 | 84 | # User-specific files (MonoDevelop/Xamarin Studio) 85 | *.userprefs 86 | 87 | # Build results 88 | [Dd]ebug/ 89 | [Dd]ebugPublic/ 90 | [Rr]elease/ 91 | [Rr]eleases/ 92 | x64/ 93 | x86/ 94 | bld/ 95 | [Bb]in/ 96 | [Oo]bj/ 97 | [Ll]og/ 98 | 99 | # Visual Studio 2015/2017 cache/options directory 100 | .vs/ 101 | # Uncomment if you have tasks that create the project's static files in wwwroot 102 | #wwwroot/ 103 | 104 | # Visual Studio 2017 auto generated files 105 | Generated\ Files/ 106 | 107 | # MSTest test Results 108 | [Tt]est[Rr]esult*/ 109 | [Bb]uild[Ll]og.* 110 | 111 | # NUNIT 112 | *.VisualState.xml 113 | TestResult.xml 114 | 115 | # Build Results of an ATL Project 116 | [Dd]ebugPS/ 117 | [Rr]eleasePS/ 118 | dlldata.c 119 | 120 | # Benchmark Results 121 | BenchmarkDotNet.Artifacts/ 122 | 123 | # .NET Core 124 | project.lock.json 125 | project.fragment.lock.json 126 | artifacts/ 127 | 128 | # StyleCop 129 | StyleCopReport.xml 130 | 131 | # Files built by Visual Studio 132 | *_i.c 133 | *_p.c 134 | *_h.h 135 | *.ilk 136 | *.meta 137 | *.obj 138 | *.iobj 139 | *.pch 140 | *.pdb 141 | *.ipdb 142 | *.pgc 143 | *.pgd 144 | *.rsp 145 | *.sbr 146 | *.tlb 147 | *.tli 148 | *.tlh 149 | *.tmp 150 | *.tmp_proj 151 | *_wpftmp.csproj 152 | *.log 153 | *.vspscc 154 | *.vssscc 155 | .builds 156 | *.pidb 157 | *.svclog 158 | *.scc 159 | 160 | # Chutzpah Test files 161 | _Chutzpah* 162 | 163 | # Visual C++ cache files 164 | ipch/ 165 | *.aps 166 | *.ncb 167 | *.opendb 168 | *.opensdf 169 | *.sdf 170 | *.cachefile 171 | *.VC.db 172 | *.VC.VC.opendb 173 | 174 | # Visual Studio profiler 175 | *.psess 176 | *.vsp 177 | *.vspx 178 | *.sap 179 | 180 | # Visual Studio Trace Files 181 | *.e2e 182 | 183 | # TFS 2012 Local Workspace 184 | $tf/ 185 | 186 | # Guidance Automation Toolkit 187 | *.gpState 188 | 189 | # ReSharper is a .NET coding add-in 190 | _ReSharper*/ 191 | *.[Rr]e[Ss]harper 192 | *.DotSettings.user 193 | 194 | # JustCode is a .NET coding add-in 195 | .JustCode 196 | 197 | # TeamCity is a build add-in 198 | _TeamCity* 199 | 200 | # DotCover is a Code Coverage Tool 201 | *.dotCover 202 | 203 | # AxoCover is a Code Coverage Tool 204 | .axoCover/* 205 | !.axoCover/settings.json 206 | 207 | # Visual Studio code coverage results 208 | *.coverage 209 | *.coveragexml 210 | 211 | # NCrunch 212 | _NCrunch_* 213 | .*crunch*.local.xml 214 | nCrunchTemp_* 215 | 216 | # MightyMoose 217 | *.mm.* 218 | AutoTest.Net/ 219 | 220 | # Web workbench (sass) 221 | .sass-cache/ 222 | 223 | # Installshield output folder 224 | [Ee]xpress/ 225 | 226 | # DocProject is a documentation generator add-in 227 | DocProject/buildhelp/ 228 | DocProject/Help/*.HxT 229 | DocProject/Help/*.HxC 230 | DocProject/Help/*.hhc 231 | DocProject/Help/*.hhk 232 | DocProject/Help/*.hhp 233 | DocProject/Help/Html2 234 | DocProject/Help/html 235 | 236 | # Click-Once directory 237 | publish/ 238 | 239 | # Publish Web Output 240 | *.[Pp]ublish.xml 241 | *.azurePubxml 242 | # Note: Comment the next line if you want to checkin your web deploy settings, 243 | # but database connection strings (with potential passwords) will be unencrypted 244 | *.pubxml 245 | *.publishproj 246 | 247 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 248 | # checkin your Azure Web App publish settings, but sensitive information contained 249 | # in these scripts will be unencrypted 250 | PublishScripts/ 251 | 252 | # NuGet Packages 253 | *.nupkg 254 | # The packages folder can be ignored because of Package Restore 255 | **/[Pp]ackages/* 256 | # except build/, which is used as an MSBuild target. 257 | !**/[Pp]ackages/build/ 258 | # Uncomment if necessary however generally it will be regenerated when needed 259 | #!**/[Pp]ackages/repositories.config 260 | # NuGet v3's project.json files produces more ignorable files 261 | *.nuget.props 262 | *.nuget.targets 263 | 264 | # Microsoft Azure Build Output 265 | csx/ 266 | *.build.csdef 267 | 268 | # Microsoft Azure Emulator 269 | ecf/ 270 | rcf/ 271 | 272 | # Windows Store app package directories and files 273 | AppPackages/ 274 | BundleArtifacts/ 275 | Package.StoreAssociation.xml 276 | _pkginfo.txt 277 | *.appx 278 | 279 | # Visual Studio cache files 280 | # files ending in .cache can be ignored 281 | *.[Cc]ache 282 | # but keep track of directories ending in .cache 283 | !*.[Cc]ache/ 284 | 285 | # Others 286 | ClientBin/ 287 | ~$* 288 | *~ 289 | *.dbmdl 290 | *.dbproj.schemaview 291 | *.jfm 292 | *.pfx 293 | *.publishsettings 294 | orleans.codegen.cs 295 | 296 | # Including strong name files can present a security risk 297 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 298 | #*.snk 299 | 300 | # Since there are multiple workflows, uncomment next line to ignore bower_components 301 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 302 | #bower_components/ 303 | 304 | # RIA/Silverlight projects 305 | Generated_Code/ 306 | 307 | # Backup & report files from converting an old project file 308 | # to a newer Visual Studio version. Backup files are not needed, 309 | # because we have git ;-) 310 | _UpgradeReport_Files/ 311 | Backup*/ 312 | UpgradeLog*.XML 313 | UpgradeLog*.htm 314 | ServiceFabricBackup/ 315 | *.rptproj.bak 316 | 317 | # SQL Server files 318 | *.mdf 319 | *.ldf 320 | *.ndf 321 | 322 | # Business Intelligence projects 323 | *.rdl.data 324 | *.bim.layout 325 | *.bim_*.settings 326 | *.rptproj.rsuser 327 | 328 | # Microsoft Fakes 329 | FakesAssemblies/ 330 | 331 | # GhostDoc plugin setting file 332 | *.GhostDoc.xml 333 | 334 | # Node.js Tools for Visual Studio 335 | .ntvs_analysis.dat 336 | node_modules/ 337 | 338 | # Visual Studio 6 build log 339 | *.plg 340 | 341 | # Visual Studio 6 workspace options file 342 | *.opt 343 | 344 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 345 | *.vbw 346 | 347 | # Visual Studio LightSwitch build output 348 | **/*.HTMLClient/GeneratedArtifacts 349 | **/*.DesktopClient/GeneratedArtifacts 350 | **/*.DesktopClient/ModelManifest.xml 351 | **/*.Server/GeneratedArtifacts 352 | **/*.Server/ModelManifest.xml 353 | _Pvt_Extensions 354 | 355 | # Paket dependency manager 356 | .paket/paket.exe 357 | paket-files/ 358 | 359 | # FAKE - F# Make 360 | .fake/ 361 | 362 | # JetBrains Rider 363 | .idea/ 364 | *.sln.iml 365 | 366 | # CodeRush personal settings 367 | .cr/personal 368 | 369 | # Python Tools for Visual Studio (PTVS) 370 | __pycache__/ 371 | *.pyc 372 | 373 | # Cake - Uncomment if you are using it 374 | # tools/** 375 | # !tools/packages.config 376 | 377 | # Tabs Studio 378 | *.tss 379 | 380 | # Telerik's JustMock configuration file 381 | *.jmconfig 382 | 383 | # BizTalk build output 384 | *.btp.cs 385 | *.btm.cs 386 | *.odx.cs 387 | *.xsd.cs 388 | 389 | # OpenCover UI analysis results 390 | OpenCover/ 391 | 392 | # Azure Stream Analytics local run output 393 | ASALocalRun/ 394 | 395 | # MSBuild Binary and Structured Log 396 | *.binlog 397 | 398 | # NVidia Nsight GPU debugger configuration file 399 | *.nvuser 400 | 401 | # MFractors (Xamarin productivity tool) working folder 402 | .mfractor/ 403 | 404 | # Local History for Visual Studio 405 | .localhistory/ -------------------------------------------------------------------------------- /AspNetCore.EventBus/RabbitMQ/EventBusRabbitMQ.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Sockets; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Logging; 7 | using Microsoft.Extensions.Options; 8 | using Newtonsoft.Json; 9 | using Newtonsoft.Json.Linq; 10 | using Polly; 11 | using RabbitMQ.Client; 12 | using RabbitMQ.Client.Events; 13 | using RabbitMQ.Client.Exceptions; 14 | 15 | namespace AspNetCore.EventBus.RabbitMQ 16 | { 17 | public class EventBusRabbitMQ : IEventBus, IDisposable 18 | { 19 | private readonly IRabbitMQPersistentConnection _persistentConnection; 20 | 21 | private readonly ILogger _logger; 22 | 23 | private readonly IEventBusSubscriptionsManager _subsManager; 24 | 25 | private IModel _consumerChannel; 26 | 27 | private readonly string _exchangeType; 28 | 29 | private readonly EventBusRabbitMQOptions _options; 30 | 31 | private readonly IServiceProvider _services; 32 | 33 | public EventBusRabbitMQ( 34 | IServiceProvider services, 35 | IOptions options, 36 | IRabbitMQPersistentConnection persistentConnection, ILogger logger, 37 | IEventBusSubscriptionsManager subsManager) 38 | { 39 | _logger = logger; 40 | 41 | _services = services; 42 | 43 | _persistentConnection = persistentConnection ?? throw new ArgumentNullException(nameof(persistentConnection)); 44 | 45 | _subsManager = subsManager ?? new EventBusSubscriptionsManager(); 46 | 47 | _options = options.Value; 48 | 49 | _exchangeType = "direct"; 50 | 51 | _consumerChannel = CreateConsumerChannel(); 52 | 53 | _subsManager.OnEventRemoved += SubsManager_OnEventRemoved; 54 | } 55 | 56 | private void SubsManager_OnEventRemoved(object sender, string eventName) 57 | { 58 | if (!_persistentConnection.IsConnected) 59 | { 60 | _persistentConnection.TryConnect(); 61 | } 62 | 63 | using var channel = _persistentConnection.CreateModel(); 64 | 65 | channel.QueueUnbind(queue: _options.QueueName, exchange: _options.BrokerName, routingKey: eventName); 66 | 67 | if (_subsManager.IsEmpty) 68 | { 69 | _consumerChannel.Close(); 70 | } 71 | } 72 | 73 | public void Publish(Event @event) 74 | { 75 | if (!_persistentConnection.IsConnected) 76 | { 77 | _persistentConnection.TryConnect(); 78 | } 79 | 80 | var policy = Policy.Handle().Or() 81 | .WaitAndRetry(_options.RetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), 82 | (ex, time) => 83 | { 84 | _logger.LogWarning(ex, 85 | "Could not publish event: {EventId} after {Timeout}s ({ExceptionMessage})", 86 | @event.Id, $"{time.TotalSeconds:n1}", ex.Message); 87 | }); 88 | 89 | using var channel = _persistentConnection.CreateModel(); 90 | 91 | var eventName = @event.GetType().Name; 92 | 93 | channel.ExchangeDeclare(exchange: _options.BrokerName, type: _exchangeType); 94 | 95 | var message = JsonConvert.SerializeObject(@event); 96 | 97 | var body = Encoding.UTF8.GetBytes(message); 98 | 99 | policy.Execute(() => 100 | { 101 | var properties = channel.CreateBasicProperties(); 102 | 103 | properties.DeliveryMode = 2; 104 | 105 | channel.BasicPublish(exchange: _options.BrokerName, routingKey: eventName, mandatory: true, 106 | basicProperties: properties, body: body); 107 | }); 108 | } 109 | 110 | public void SubscribeDynamic(string eventName) where TH : IDynamicEventHandler 111 | { 112 | DoInternalSubscription(eventName); 113 | 114 | _logger.LogInformation("Subscribing to dynamic event {EventName} with {EventHandler}", eventName, 115 | typeof(TH).GetGenericTypeName()); 116 | 117 | _subsManager.AddDynamicSubscription(eventName); 118 | 119 | StartBasicConsume(); 120 | } 121 | 122 | public void Subscribe() where T : Event where TH : IEventHandler 123 | { 124 | var eventName = _subsManager.GetEventKey(); 125 | 126 | DoInternalSubscription(eventName); 127 | 128 | _logger.LogInformation("Subscribing to dynamic event {EventName} with {EventHandler}", eventName, 129 | typeof(TH).GetGenericTypeName()); 130 | 131 | _subsManager.AddSubscription(); 132 | 133 | StartBasicConsume(); 134 | } 135 | 136 | private void DoInternalSubscription(string eventName) 137 | { 138 | var containsKey = _subsManager.HasSubscriptionsForEvent(eventName); 139 | 140 | if (!containsKey) 141 | { 142 | if (!_persistentConnection.IsConnected) 143 | { 144 | _persistentConnection.TryConnect(); 145 | } 146 | 147 | using var channel = _persistentConnection.CreateModel(); 148 | 149 | channel.QueueBind(queue: _options.QueueName, exchange: _options.BrokerName, routingKey: eventName); 150 | } 151 | } 152 | 153 | public void Unsubscribe() where TH : IEventHandler where T : Event 154 | { 155 | var eventName = _subsManager.GetEventKey(); 156 | 157 | _logger.LogInformation("Unsubscribing from event {EventName}", eventName); 158 | 159 | _subsManager.RemoveSubscription(); 160 | } 161 | 162 | public void UnsubscribeDynamic(string eventName) where TH : IDynamicEventHandler 163 | { 164 | _logger.LogInformation("Unsubscribing from event {EventName}", eventName); 165 | 166 | _subsManager.RemoveDynamicSubscription(eventName); 167 | } 168 | 169 | public void Dispose() 170 | { 171 | _consumerChannel?.Dispose(); 172 | 173 | _subsManager.Clear(); 174 | } 175 | 176 | private void StartBasicConsume() 177 | { 178 | _logger.LogTrace("Starting RabbitMQ basic consume"); 179 | 180 | if (_consumerChannel != null) 181 | { 182 | var consumer = new EventingBasicConsumer(_consumerChannel); 183 | 184 | consumer.Received += Consumer_Received; 185 | 186 | _consumerChannel.BasicConsume(queue: _options.QueueName, autoAck: false, consumer: consumer); 187 | } 188 | else 189 | { 190 | _logger.LogError("StartBasicConsume can't call on _consumerChannel == null"); 191 | } 192 | } 193 | 194 | private async void Consumer_Received(object model, BasicDeliverEventArgs eventArgs) 195 | { 196 | var eventName = eventArgs.RoutingKey; 197 | 198 | var message = Encoding.UTF8.GetString(eventArgs.Body.Span); 199 | 200 | var processed = false; 201 | 202 | try 203 | { 204 | processed = await ProcessEvent(eventName, message); 205 | } 206 | catch (Exception ex) 207 | { 208 | _logger.LogWarning(ex, "----- ERROR Processing message \"{Message}\"", message); 209 | } 210 | 211 | if (processed) 212 | { 213 | _consumerChannel.BasicAck(eventArgs.DeliveryTag, multiple: false); 214 | } 215 | else 216 | { 217 | _consumerChannel.BasicNack(eventArgs.DeliveryTag, false, true); 218 | } 219 | } 220 | 221 | private IModel CreateConsumerChannel() 222 | { 223 | if (!_persistentConnection.IsConnected) 224 | { 225 | _persistentConnection.TryConnect(); 226 | } 227 | 228 | _logger.LogTrace("Creating RabbitMQ consumer channel"); 229 | 230 | var channel = _persistentConnection.CreateModel(); 231 | 232 | channel.ExchangeDeclare(exchange: _options.BrokerName, type: _exchangeType); 233 | 234 | channel.QueueDeclare(queue: _options.QueueName, durable: true, exclusive: false, autoDelete: false, arguments: null); 235 | 236 | _logger.LogInformation($"Queue [{_options.QueueName}] declared"); 237 | 238 | channel.CallbackException += (sender, ea) => 239 | { 240 | _logger.LogWarning(ea.Exception, "Recreating RabbitMQ consumer channel"); 241 | 242 | _consumerChannel.Dispose(); 243 | 244 | _consumerChannel = CreateConsumerChannel(); 245 | 246 | StartBasicConsume(); 247 | }; 248 | 249 | _logger.LogInformation("Channel Created!"); 250 | 251 | return channel; 252 | } 253 | 254 | private async Task ProcessEvent(string eventName, string message) 255 | { 256 | var processed = false; 257 | 258 | if (_subsManager.HasSubscriptionsForEvent(eventName)) 259 | { 260 | using (var scope = _services.CreateScope()) 261 | { 262 | var subscriptions = _subsManager.GetHandlersForEvent(eventName); 263 | 264 | foreach (var subscription in subscriptions) 265 | { 266 | if (subscription.IsDynamic) 267 | { 268 | if (!(scope.ServiceProvider.GetRequiredService(subscription.HandlerType) is IDynamicEventHandler handler)) 269 | { 270 | throw new NullReferenceException($"Cannot find EventHandler, type {subscription.HandlerType.Name}"); 271 | } 272 | 273 | dynamic eventData = JObject.Parse(message); 274 | 275 | await handler.Handle(eventData); 276 | } 277 | else 278 | { 279 | var eventType = _subsManager.GetEventTypeByName(eventName); 280 | 281 | var integrationEvent = JsonConvert.DeserializeObject(message, eventType); 282 | 283 | var handler = scope.ServiceProvider.GetRequiredService(subscription.HandlerType); 284 | 285 | var concreteType = typeof(IEventHandler<>).MakeGenericType(eventType); 286 | 287 | await (Task)concreteType.GetMethod("Handle").Invoke(handler, new[] { integrationEvent }); 288 | } 289 | } 290 | } 291 | 292 | processed = true; 293 | } 294 | else 295 | { 296 | _logger.LogWarning("No subscription for RabbitMQ event: {EventName}", eventName); 297 | } 298 | 299 | return processed; 300 | } 301 | } 302 | } --------------------------------------------------------------------------------