{"id":22938394,"url":"https://github.com/jacraig/canister","last_synced_at":"2025-07-11T08:07:24.794Z","repository":{"id":60772326,"uuid":"72221117","full_name":"JaCraig/Canister","owner":"JaCraig","description":"Canister is a simple C# library aimed at enhancing the built-in IoC container in .NET. It enables you to effortlessly add all objects of a specified type and introduces the concept of modules to automatically wire up your system. With Canister, managing dependencies becomes a breeze, allowing you to focus on writing maintainable code.","archived":false,"fork":false,"pushed_at":"2024-12-09T04:17:14.000Z","size":22805,"stargazers_count":7,"open_issues_count":0,"forks_count":2,"subscribers_count":6,"default_branch":"master","last_synced_at":"2024-12-09T05:21:00.499Z","etag":null,"topics":["dependency-injection","inversion-of-control","ioc","ioc-container"],"latest_commit_sha":null,"homepage":"https://jacraig.github.io/Canister/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/JaCraig.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-10-28T15:51:05.000Z","updated_at":"2024-12-09T04:16:22.000Z","dependencies_parsed_at":"2024-03-26T22:27:08.573Z","dependency_job_id":"442c7f85-02d5-4f47-b18e-5748c2735afd","html_url":"https://github.com/JaCraig/Canister","commit_stats":{"total_commits":78,"total_committers":5,"mean_commits":15.6,"dds":"0.34615384615384615","last_synced_commit":"1740724bbc001d83c7ee3682fc89bdafce33ed53"},"previous_names":[],"tags_count":49,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JaCraig%2FCanister","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JaCraig%2FCanister/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JaCraig%2FCanister/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JaCraig%2FCanister/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JaCraig","download_url":"https://codeload.github.com/JaCraig/Canister/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":229700170,"owners_count":18109927,"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":["dependency-injection","inversion-of-control","ioc","ioc-container"],"created_at":"2024-12-14T12:17:48.661Z","updated_at":"2025-07-11T08:07:24.778Z","avatar_url":"https://github.com/JaCraig.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# \u003cimg src=\"https://jacraig.github.io/Canister/images/icon.png\" style=\"height:25px\" alt=\"Canister Icon\" /\u003e Canister\n\n[![.NET Publish](https://github.com/JaCraig/Canister/actions/workflows/dotnet-publish.yml/badge.svg)](https://github.com/JaCraig/Canister/actions/workflows/dotnet-publish.yml) [![Coverage Status](https://coveralls.io/repos/github/JaCraig/Canister/badge.svg?branch=master)](https://coveralls.io/github/JaCraig/Canister?branch=master) [![NuGet](https://img.shields.io/nuget/v/Canister.IoC.svg)](https://www.nuget.org/packages/Canister.IoC/)\n\nCanister is one of the easiest ways to get IoC configuration under control. No longer do you have to search for that one class that you forgot to register. Instead use Canister to handle discovery and registration for you using a simple interface.\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [Basic Usage](#basic-usage)\n- [Modules](#modules)\n- [Attributes](#attributes)\n- [Canister Extension Methods](#canister-extension-methods)\n- [Working With Other IoC Containers](#working-with-other-ioc-containers)\n- [Using Canister in Your Library](#using-canister-in-your-library)\n- [Installation](#installation)\n- [Build Process](#build-process)\n\n## Quick Start\n\n```csharp\nusing Microsoft.Extensions.DependencyInjection;\n\nvar services = new ServiceCollection();\nservices.AddCanisterModules();\nvar provider = services.BuildServiceProvider();\n```\n\nFor a more detailed example, you can check out the [Canister Example](https://jacraig.github.io/Canister/articles/intro.html) which demonstrates how to use Canister in a couple simple scenarios.\n\n## Basic Usage\n\nThe system has a fairly simple interface and only a couple of functions that need explaining. The first is setup:\n\n```csharp\n    public void ConfigureServices(IServiceCollection services)\n    {\n        ...\n        services.AddCanisterModules();\n    }\n```\n\nAddCanisterModules will automatically scan assemblies for modules and load them accordingly. Or if you're doing a desktop app:\n\n```csharp\n    var Services = new ServiceCollection().AddCanisterModules();\n```\n\nNote that if you like, you can control which assemblies are searched:\n\n```csharp\n    public void ConfigureServices(IServiceCollection services)\n    {\n        ...\n        services.AddCanisterModules(configure =\u003e configure.AddAssembly(typeof(Startup).Assembly));\n    }\n```\n\n\u003e **Note:** For security reasons, it's recommended to explicitly specify which assemblies to scan. By default, Canister will search all assemblies found in the entry assembly's top-level directory.\n\nIt is also possible to add logging to the system while configuring it. This is useful for debugging purposes or to get insights into the registration process. You can do this by passing an `ILogger` instance to the `UseLogger` method along with a default log level:\n\n```csharp\n    public void ConfigureServices(IServiceCollection services, ILogger logger)\n    {\n        ...\n        services.AddCanisterModules().UseLogger(logger, LogLevel.Information);\n    }\n```\n\n## Modules\n\nCanister uses the concept of modules to wire things up, but is not a requirement. This allows you to place registration code in libraries that your system is using instead of worrying about it in every application. Simply add your library and Canister will automatically wire it up for you. In order to do this, under Canister.Interfaces there is the IModule interface. This interface, when implemented, has two items in it. The first is a property called Order. This determines the order that the modules are loaded in. The second is a function called Load:\n\n```csharp\n    public class TestModule : IModule\n    {\n        public int Order =\u003e 1;\n\n        public void Load(IServiceCollection bootstrapper)\n        {\n\t\t    bootstrapper.AddAllTransient\u003cIMyInterface\u003e();\n\t\t\tbootstrapper.AddTransient\u003cMyType\u003e();\n        }\n    }\n```\n\nThe module above is loaded automatically by the system and will have the Load function called at initialization time. At this point you should be able to resolve and register classes using the bootstrapper parameter. The service collection also has a couple of extra extension methods: AddAllTransient, AddAllScoped, AddAllSingleton:\n\n```csharp\n    bootstrapper.AddAllTransient\u003cIMyInterface\u003e();\n```\n\nThe AddAllxxxx functions will find everything that implements a class or interface in the Assemblies that you tell it to look in and will register them with the service collection.\n\n## Attributes\n\nCanister also allows for attributes to be used to control registration. There are two attributes that the system uses:\n\n- RegisterAttribute - This attribute is used to control how a class is registered. It will register the class as all interfaces that it implements as well as the class itself. The attribute takes the life time of the registration as a parameter. If no parameter is given, the registration will be transient. It also can take a service key as well.\n\n```csharp\n    [Register(LifeTime.Singleton)]\n    public class MyType : IMyInterface\n    {\n    }\n```\n\n- RegisterAllAttribute - This attribute is used to control how an interface is registered. It will register all classes that implement the interface similar to the AddAllxxxx functions. The attribute takes the life time of the registration as a parameter. If no parameter is given, the registration will be transient.\n\n```csharp\n    [RegisterAll(LifeTime.Singleton)]\n    public interface IMyInterface\n    {\n    }\n```\n\n### Canister Extension Methods\n\nCanister provides a set of extension methods to streamline your IoC (Inversion of Control) container registration code. These methods offer convenient ways to conditionally register services based on certain criteria, enhancing the flexibility of your application's dependency injection setup. Note that these can be used even if you are not using the Canister modules.\n\n#### 1. `AddTransientIf()`\n\nThe `AddTransientIf` method registers a service as transient only if a specified condition is met. This is useful when you want to dynamically determine whether a service should be transient or not.\n\n```csharp\nservices.AddTransientIf\u003cIMyService, MyService\u003e(services =\u003e condition);\n```\n\n#### 2. `AddScopedIf()`\n\nSimilar to `AddTransientIf`, `AddScopedIf` registers a service as scoped based on a given condition.\n\n```csharp\nservices.AddScopedIf\u003cIMyScopedService, MyScopedService\u003e(services =\u003e condition);\n```\n\n#### 3. `AddSingletonIf()`\n\nThe `AddSingletonIf` method registers a service as a singleton if the specified condition holds true.\n\n```csharp\nservices.AddSingletonIf\u003cIMySingletonService, MySingletonService\u003e(services =\u003e condition);\n```\n\n#### 4. `AddKeyedTransientIf()`, `AddKeyedScopedIf()`, `AddKeyedSingletonIf()`\n\nThese methods follow the same pattern as their non-keyed counterparts but additionally allow you to register services with a specified key.\n\n```csharp\nservices.AddKeyedTransientIf\u003cIService\u003e(key, implementationType, (services, key) =\u003e condition);\n```\n\n#### 5. `Exists()`\n\nThe `Exists` method checks whether a service with a specific type and, optionally, a key, has already been registered. This can be helpful in avoiding duplicate registrations or finding issues with your environment before starting the application.\n\n```csharp\nif (!services.Exists\u003cIMyService\u003e())\n{\n    services.AddTransient\u003cIMyService, MyService\u003e();\n}\n```\n\n#### 6. `AddAllTransient()`, `AddAllScoped()`, `AddAllSingleton()`\n\nThese methods allow you to register all implementations of a given interface or class as transient, scoped, or singleton services, respectively. They are particularly useful for bulk registrations.\n\n```csharp\nservices.AddAllTransient\u003cIMyService\u003e();\nservices.AddAllScoped\u003cIMyScopedService\u003e();\nservices.AddAllSingleton\u003cIMySingletonService\u003e();\n```\n\n#### 7. `TryAddAllTransient()`, `TryAddAllScoped()`, `TryAddAllSingleton()`\n\nThese methods attempt to register all implementations of a given interface or class as transient, scoped, or singleton services, but only if they have not already been registered. This is useful for ensuring that you do not accidentally override existing registrations.\n\n```csharp\nservices.TryAddAllTransient\u003cIMyService\u003e();\nservices.TryAddAllScoped\u003cIMyScopedService\u003e();\nservices.TryAddAllSingleton\u003cIMySingletonService\u003e();\n```\n\n#### 8. `Decorate()`\n\nThe `Decorate` method allows you to wrap an existing service with a decorator. This is useful for adding additional behavior to a service without modifying its original implementation.\n\n```csharp\nservices.Decorate\u003cIMyService, MyServiceDecorator\u003e();\n```\n\n#### 9. `AddCanisterModules()`\n\nThe `AddCanisterModules` method is used to automatically discover and register modules that implement the `IModule` interface. This method scans the specified assemblies for modules and loads them, allowing you to organize your service registrations in a modular way.\n\n```csharp\nservices.AddCanisterModules(config =\u003e\n{\n    // Optionally specify which assemblies to scan\n    config.AddAssembly(typeof(MyModule).Assembly)\n          .UseLogger(logger, LogLevel.Information);\n});\n```\n\n#### 10. `GetRegistrationsSummary()`\n\nThe `GetRegistrationsSummary` method provides a summary of all registered services in the IoC container. This can be useful for debugging and understanding what services are available in your application.\n\n```csharp\nvar summary = services.GetRegistrationsSummary();\nlogger.LogInformation(\"Service Registrations: {Summary}\", summary);\n```\n\n### Usage Example\n\nHere's an example of how you might use these methods:\n\n```csharp\n\nIHostEnvironment? environment;\n\n// Conditionally register a transient service if in development environment.\nservices.AddTransientIf\u003cIMyService, MyDebugService\u003e(_ =\u003e environment.IsDevelopment());\n\n// However if you're in production, add a different implementation.\nservices.AddTransientIf\u003cIMyService, MyProductionService\u003e(_ =\u003e environment.IsProduction());\n\n// Check if a keyed service is missing and log a warning if so.\nif (!services.Exists\u003cIService\u003e(key))\n{\n    logger.LogWarning(\"Service {Service} is missing\", key);\n}\n\n```\n\nThese methods empower you to create more dynamic and adaptive dependency injection configurations tailored to your application's requirements.\n\n## Working With Other IoC Containers\n\nWhile the library assumes you are using the built in ServiceCollection, it is possible to work with IoC containers. All that is required is that it implements the IServiceCollection interface.\n\n## Using Canister in Your library\n\nIf you wish to use Canister in your library, it is recommended that you build an extension method off of the ICanisterConfiguration interface that will allow you to register your needed assemblies for the user to make the experience a bit simpler when they want to control configuration themselves.\n\n## Installation\n\nThe library is available via Nuget with the package name \"Canister.IoC\". To install it run the following command in the Package Manager Console:\n\n```powershell\ndotnet add package Canister.IoC\n```\n\n## Build Process\n\nIn order to build the library you may require the following:\n\n1. Visual Studio 2022\n\nOther than that, just clone the project and you should be able to load the solution and build without too much effort.\n\n## License\n\nThis project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.\n\n## Contributing\n\nIf you would like to contribute to the project, please fork the repository and submit a pull request. Contributions are welcome, and we appreciate any help in improving the library. Please refer to the [Contributing Guide](CONTRIBUTING.md) for more details on how to contribute.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjacraig%2Fcanister","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjacraig%2Fcanister","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjacraig%2Fcanister/lists"}