{"id":19068436,"url":"https://github.com/bobbylite/dotnetcoredependencyinjection","last_synced_at":"2025-10-03T18:04:44.631Z","repository":{"id":116629141,"uuid":"285942784","full_name":"bobbylite/DotNetCoreDependencyInjection","owner":"bobbylite","description":"Dependency Injection scaffolding for .NET Core ","archived":false,"fork":false,"pushed_at":"2022-04-07T16:37:31.000Z","size":912,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-02T15:19:13.148Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bobbylite.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-08-08T00:11:20.000Z","updated_at":"2022-04-07T16:37:34.000Z","dependencies_parsed_at":"2023-07-21T12:01:13.420Z","dependency_job_id":null,"html_url":"https://github.com/bobbylite/DotNetCoreDependencyInjection","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bobbylite%2FDotNetCoreDependencyInjection","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bobbylite%2FDotNetCoreDependencyInjection/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bobbylite%2FDotNetCoreDependencyInjection/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bobbylite%2FDotNetCoreDependencyInjection/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bobbylite","download_url":"https://codeload.github.com/bobbylite/DotNetCoreDependencyInjection/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240122465,"owners_count":19751139,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-09T01:08:05.884Z","updated_at":"2025-10-03T18:04:39.572Z","avatar_url":"https://github.com/bobbylite.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Decoupled Dependency Injection Application [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=bobbylite%20.NET%20Core%20toolkit\u0026url=https://github.com/bobbylite/DotNetCoreDependencyInjection\u0026hashtags=Inversion-of-Control,Events,bobbylite)\nbobbylite DotNetCoreDependencyInjection is a dependency injection application scaffold that utilizes Microsoft's built in inversion of control dependency injection to decouple registered services, events, and handlers.\n\n## Run example\nRun the following in your terminal.\n\n### Clone the code \n```bash\ngit clone https://github.com/bobbylite/DotNetCoreDependencyInjection\ncd DotNetCoreDependencyInjection\n```\n### .NET Reference Guide\nTo add as a library reference you can refer to this documentation.\nhttps://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-add-reference\n\n\n### Hot to build\n```bash\ndotnet build\n```\n\n### How to run\n```bash\ndotnet run --project DotNetCoreDependencyInjection.csproj\n```\n\n## How to use in project\n\n### Step 1 - Implement Service\nLet's setup a simple WebEndpoint Service. We want this to start automatically when the app runs and stop automatically when the app stops... So we can implement the IAutoStart interface provided. \n```csharp \nusing Microsoft.Extensions.Logging;\nusing DependencyInjectionApp.Common;\n\nnamespace DependencyInjectionApp.Services \n{\n    public class WebEndpointService : IAutoStart\n    {\n        public readonly ILogger\u003cWebEndpointService\u003e _logger;\n\n        public WebEndpointService(ILogger\u003cWebEndpointService\u003e logger)\n        { \n            _logger = logger;\n        }\n        \n        public void Start() \n        {\n            _logger.LogInformation(\"Web Endpoint Started!\");\n        }\n\n        public void Stop()\n        {\n            _logger.LogInformation(\"Web Endpoint Stopped.\");\n        }\n    }\n}\n```\n\n### Step 2 - Register Service\nWe must then let the dependency injection container know that the service is available. We do this by registering the class in the ServicesModule class. Registering with AddSinglton\u003cinterface, class\u003e() will instantiate one instance that the container manages. \n```csharp\nusing DependencyInjectionApp.Services;\nusing DependencyInjectionApp.Common;\nusing Microsoft.Extensions.DependencyInjection;\n\nnamespace DependencyInjectionApp.DependencyInjection\n{\n    public class ServicesModule : BaseModule \n    {\n        protected override void RegisterServiceModule(IServiceCollection serviceModule)\n        {\n            serviceModule.AddSingleton\u003cIAutoStart, WebEndpointService\u003e();\n        }\n    }\n}\n```\n\n### Step 3 - Implment Notifications\nNotifications will be broken into two steps. The Notification itself, which can be used anywhere in the application and then the actual notification handler.  You get to tell the handler how to handle the notification object and you get to tell the notification object what is contained inside of it. \n #### Creating a notification\n Let's create a simple notification that contains a string. \n ```csharp\nusing DependencyInjectionApp.Common;\n\nnamespace DependencyInjectionApp.Notifications\n{\n    public class ApplicationStartedNotification : INotification\n    {\n        public string ApllicationStartedMessage {get; set;}\n    }\n}\n ```\n#### Creating a notification handler\nLet's create a handler that receives the notification, grabs the string and logs it. We must use the BaseNotificationHanlder\u003cT\u003e interface to allow us to handle notifications on the back end later on. \n```csharp\nusing DependencyInjectionApp.Notifications;\nusing Microsoft.Extensions.Logging;\n\nnamespace DependencyInjectionApp.NotificationHandlers\n{\n    public class ApplicationStartedNotificationHandler : BaseNotificationHandler\u003cApplicationStartedNotification\u003e\n    {\n        public readonly ILogger\u003cApplicationStartedNotificationHandler\u003e _logger;\n        \n        public ApplicationStartedNotificationHandler(ILogger\u003cApplicationStartedNotificationHandler\u003e logger)\n        {\n            _logger = logger;\n        }\n        protected override void HandleNotification(ApplicationStartedNotification notification)\n        {\n            _logger.LogInformation($\"MESSAGE: {notification.ApllicationStartedMessage}\");\n        }\n    }\n}\n```\n\n#### Registering the notification handler to the notification event\nIn the application dependecy injection module we can register the notification handler to be explicitly associated with our newly created notification. Registering with AddTransient\u003cinterface, class\u003e() will instantiate a new instance everytime it is resolved.\n```csharp\nusing DependencyInjectionApp.Services;\nusing Microsoft.Extensions.DependencyInjection;\nusing DependencyInjectionApp.NotificationHandlers;\nusing DependencyInjectionApp.Notifications;\nusing DependencyInjectionApp.Common;\n\nnamespace DependencyInjectionApp.DependencyInjection.Modules\n{\n    public class ApplicationModule : BaseModule \n    {\n        protected override void RegisterServiceModule(IServiceCollection serviceModule)\n        {\n            // Register application handlers\n            serviceModule.AddTransient\u003cIHandleNotifications\u003cApplicationStartedNotification\u003e, ApplicationStartedNotificationHandler\u003e();\n\n            // Register Notification Manager \n            serviceModule.AddSingleton\u003cINotificationManager, NotificationManager\u003e();\n            \n            // Startup application\n            serviceModule.AddHostedService\u003cAppStartupService\u003e();\n        }\n```\n\n#### Using our new notification\nWe can call our notification handler from any class that's already registered. In this case, let's use our Web Endpoint class.\nWe will send a start and end notification to our handler. Earlier we decided that our handler will just print the notification string.\n```csharp\nusing Microsoft.Extensions.Logging;\nusing DependencyInjectionApp.Common;\nusing DependencyInjectionApp.Notifications;\n\nnamespace DependencyInjectionApp.Services \n{\n    public class WebEndpointService : IAutoStart\n    {\n        public readonly ILogger\u003cWebEndpointService\u003e _logger;\n        public readonly INotificationManager _notificationManager;\n\n        public WebEndpointService(INotificationManager notificationManager, ILogger\u003cWebEndpointService\u003e logger)\n        { \n            _logger = logger;\n            _notificationManager = notificationManager;\n        }\n        \n        public void Start() \n        {\n            _notificationManager.Notify(new ApplicationStartedNotification{\n                ApllicationStartedMessage = \"Endpoint Started Notification\"\n            });\n        }\n\n        public void Stop()\n        {\n            _notificationManager.Notify(new ApplicationStartedNotification{\n                ApllicationStartedMessage = \"Endpoint Stopped Notification\"\n            });\n        }\n    }\n}\n```\n\n## Behind the scenes\nBehind the scenes we have two important files that really auto-wire up the notifications to the handlers.\nThis .NET Core lib uses Microsoft's DI container to auto-wire everything in the background. Out of the box\nyou have NotificationManager because of this Core Module. \nTake a look below.\n\n### Notifications\nLet's take a look at how notifications are decoupled on the back end. \n\n#### Base notification handler \nWhen creating a new notification handler we have to inherit the IHandleNotifications interface. This will allow us to later use the service provider to grab the services registered with an associated type. \n```csharp\nusing DependencyInjectionApp.Common;\n\nnamespace DependencyInjectionApp.NotificationHandlers \n{\n    public abstract class BaseNotificationHandler\u003cT\u003e : IHandleNotifications\u003cT\u003e where T : INotification\n    {\n        public void Handle(T notification)\n        {\n            try\n            {\n                HandleNotification(notification);\n            } \n            catch\n            {\n                // Handle error\n            }\n        }\n\n        protected abstract void HandleNotification(T notification);\n    }\n}\n```\n#### Notification manager\nThe notification manager's job is to use the service provider to find which handler you are trying to notify, and call that handlers handle() method. \n```csharp\nusing DependencyInjectionApp.Common;\nusing System;\nusing Microsoft.Extensions.DependencyInjection;\n\nnamespace DependencyInjectionApp.DependencyInjection\n{\n    public class NotificationManager : INotificationManager\n    {\n        public readonly IServiceProvider _serviceProvider;\n\n        public NotificationManager(IServiceProvider serviceProvider)\n        {\n            _serviceProvider = serviceProvider;\n        }\n\n        public void Notify\u003cT\u003e(T notification) where T : INotification\n        {\n            HanldeNotification(_serviceProvider, notification);\n        }\n\n        private static void HanldeNotification\u003cT\u003e(IServiceProvider serviceProvider, T notification) where T : INotification\n        {\n            var registeredNotificationHandlers = serviceProvider.GetServices\u003cIHandleNotifications\u003cT\u003e\u003e();\n            foreach (var handler in registeredNotificationHandlers)\n            {\n                handler.Handle(notification);\n            }\n        }\n    }\n}\n```\n\n#### Base Module\n```csharp\nusing Microsoft.Extensions.DependencyInjection;\nusing DependencyInjectionApp.Common;\n\nnamespace DependencyInjectionApp.DependencyInjection\n{\n    public abstract class BaseModule : IBaseModule \n    {\n        public void BuildModule(IServiceCollection service)\n        {\n            try \n            {\n                RegisterServiceModule(service);\n            } catch\n            {\n                // Handle \n            }\n        }\n\n        protected abstract void RegisterServiceModule(IServiceCollection serviceModule);\n    }\n}\n```\n\n#### Application Startup Service\nThis is the service that identifies objects that are registered as auto start classes. \n```csharp\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing DependencyInjectionApp.Common;\nusing System;\nusing System.Threading.Tasks;\nusing System.Threading;\n\nnamespace DependencyInjectionApp.Services\n{\n    public class AppStartupService : IHostedService\n    {\n        private readonly IServiceProvider _serviceProvider;\n        private readonly ILogger\u003cAppStartupService\u003e _logger;\n\n        public AppStartupService(IServiceProvider provider, ILogger\u003cAppStartupService\u003e logger)\n        {\n            _serviceProvider = provider;\n            _logger = logger;\n        }\n\n        public Task StartAsync(CancellationToken cancellationToken)\n        {\n            Task.Run(() =\u003e\n            {\n                try\n                {\n                    _logger.LogInformation(\"Starting application...\");\n                }\n                catch (Exception exception)\n                {\n                    _logger.LogError(exception.StackTrace);\n                }\n            }, cancellationToken);\n\n            return AutoHandleTask(ServiceActions.Start);\n        }\n\n        public Task StopAsync(CancellationToken cancellationToken)\n        {\n            try\n            {\n                _logger.LogInformation(\"Stopping application...\");\n            }\n            catch (Exception exception)\n            {\n                _logger.LogError(exception.StackTrace);\n            }\n\n            return AutoHandleTask(ServiceActions.Stop);\n        }\n\n        private Task AutoHandleTask(ServiceActions action)\n        {\n            var registeredAutoStartServices = _serviceProvider.GetServices\u003cIAutoStart\u003e();\n            foreach (var registeredService in registeredAutoStartServices)\n            {\n                Task.Run(() =\u003e\n                {\n                    try\n                    {\n                        if (action.Equals(ServiceActions.Start)) registeredService.Start();\n                        if (action.Equals(ServiceActions.Stop)) registeredService.Stop();\n                    }\n                    catch (Exception exception)\n                    {\n                        _logger.LogError(exception.StackTrace);\n                    }\n                });\n            }\n\n            return Task.CompletedTask;\n        }\n\n        private enum ServiceActions\n        {\n            Start,\n            Stop\n        }\n    }\n}\n```\n\n#### Application Startup Registration\nThis is the entry point for our auto start objects.\n```csharp\nusing DependencyInjectionApp.Services;\nusing Microsoft.Extensions.DependencyInjection;\n\nnamespace DependencyInjectionApp.DependencyInjection\n{\n    public class ApplicationModule : BaseModule \n    {\n        protected override void RegisterServiceModule(IServiceCollection serviceModule)\n        {\n            serviceModule.AddHostedService\u003cAppStartupService\u003e();\n        }\n    }\n}\n```\n\n### App\nThis is the entry point for the application. \n```csharp\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.Logging;\nusing DependencyInjectionApp.DependencyInjection;\n\nnamespace DependencyInjectionApp\n{\n    public class App\n    {\n        public static void Main(string[] args) =\u003e HostBuilder(args).Build().Run();\n        public static IHostBuilder HostBuilder(string[] args) =\u003e\n            Host.CreateDefaultBuilder(args)\n                .ConfigureLogging(logging=\u003e\n                {\n                    logging.AddConsole();\n                    logging.AddFile(\"./dependencyInjectionApp/logs/AppLog.log\");\n                })\n                .ConfigureAppConfiguration((hostingContext, config)\n                    =\u003e config.AddJsonFile(\"appsettings.json\", optional: false, reloadOnChange: false))\n                .ConfigureServices((services) =\u003e new ApplicationModule().BuildModule(services))\n                .ConfigureServices((services) =\u003e new ServicesModule().BuildModule(services));\n    }\n}\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbobbylite%2Fdotnetcoredependencyinjection","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbobbylite%2Fdotnetcoredependencyinjection","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbobbylite%2Fdotnetcoredependencyinjection/lists"}