├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── analysis_options.yaml ├── example └── injector_example.dart ├── injector.iml ├── lib ├── injector.dart └── src │ ├── exception │ ├── already_defined_exception.dart │ ├── circular_dependency_exception.dart │ └── not_defined_exception.dart │ ├── factory │ └── factory.dart │ └── injector_base.dart ├── pubspec.yaml └── test ├── injector_test.dart ├── test_classes.dart └── test_classes_2.dart /.gitignore: -------------------------------------------------------------------------------- 1 | # Files and directories created by pub 2 | .dart_tool/ 3 | .packages 4 | .pub/ 5 | build/ 6 | # Remove the following pattern if you wish to check in your lock file 7 | pubspec.lock 8 | 9 | # Directory created by dartdoc 10 | doc/api/ 11 | 12 | # Directory created by IntelliJ 13 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 14 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 15 | 16 | .idea/ 17 | 18 | # User-specific stuff 19 | .idea/**/workspace.xml 20 | .idea/**/tasks.xml 21 | .idea/**/usage.statistics.xml 22 | .idea/**/dictionaries 23 | .idea/**/shelf 24 | 25 | # Sensitive or high-churn files 26 | .idea/**/dataSources/ 27 | .idea/**/dataSources.ids 28 | .idea/**/dataSources.local.xml 29 | .idea/**/sqlDataSources.xml 30 | .idea/**/dynamic.xml 31 | .idea/**/uiDesigner.xml 32 | .idea/**/dbnavigator.xml 33 | 34 | # Gradle 35 | .idea/**/gradle.xml 36 | .idea/**/libraries 37 | 38 | # Gradle and Maven with auto-import 39 | # When using Gradle or Maven with auto-import, you should exclude module files, 40 | # since they will be recreated, and may cause churn. Uncomment if using 41 | # auto-import. 42 | # .idea/modules.xml 43 | # .idea/*.iml 44 | # .idea/modules 45 | 46 | # CMake 47 | cmake-build-*/ 48 | 49 | # Mongo Explorer plugin 50 | .idea/**/mongoSettings.xml 51 | 52 | # File-based project format 53 | *.iws 54 | 55 | # IntelliJ 56 | out/ 57 | 58 | # mpeltonen/sbt-idea plugin 59 | .idea_modules/ 60 | 61 | # JIRA plugin 62 | atlassian-ide-plugin.xml 63 | 64 | # Cursive Clojure plugin 65 | .idea/replstate.xml 66 | 67 | # Crashlytics plugin (for Android Studio and IntelliJ) 68 | com_crashlytics_export_strings.xml 69 | crashlytics.properties 70 | crashlytics-build.properties 71 | fabric.properties 72 | 73 | # Editor-based Rest Client 74 | .idea/httpRequests 75 | 76 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: dart 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 4.0.0 2 | - Removed deprecated function `getDependency`. Use `get` instead 3 | 4 | # 3.0.0 5 | - Rename `Builder` to `DependencyBuilder` by [saibotma](https://github.com/tappeddev/injector/pull/37) 6 | 7 | # 2.0.0 8 | - Stable release for null safety 9 | 10 | 11 | ## 1.0.9 12 | - Add `get` as shortcut for `getDependency` 13 | - Add deprecated annotation to `getDependency` 14 | - Some preparations for nullability 15 | - [bug] Fixed the bug, that the library detects a wrong circular dependency ([#25][i25]) 16 | 17 | [i25]: https://github.com/tappeddev/injector/issues/25 18 | 19 | ## 1.0.8 20 | - Add travis ci badge to readme 21 | - Reformat using dartfmt 22 | 23 | ## 1.0.7 24 | - Refactor docs 25 | 26 | ## 1.0.6 27 | 28 | - Add remove dependency method 29 | - Add override dependencies property 30 | 31 | ## 1.0.5 32 | 33 | - **Breaking Changes!** Injector is not a singleton. 34 | You can use it like a singleton with the static instance ```Injector.appInstance``` 35 | - You can register your dependencies with a name. But be careful, 36 | you need always the generic type! It looks like ```Injector.allInstance.registerDependency((injector) => UserServiceImpl), dependencyName: "MyCustomName"); ``` 37 | 38 | ## 1.0.4 39 | 40 | - Add some documentation for each class 41 | 42 | 43 | ## 1.0.3 44 | 45 | - Change license from BSD-3 to Apache 2 46 | 47 | ## 1.0.2 48 | 49 | - Upgrade analysis_options.yaml 50 | - Add missing Cast ("as T") 51 | - Add Test - Cycle dependencies 52 | 53 | ## 1.0.1 54 | 55 | - Upgrade pubspec.yaml (Change dart sdk constraint) 56 | - Update README.md 57 | - Update Description 58 | 59 | 60 | ## 1.0.0 61 | 62 | - Create package, 63 | - Add Injector class 64 | - Add unit tests for "Injector" 65 | - Add example - How to deal with the injector / dependency injector 66 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Injector 💉 [![Build Status](https://travis-ci.com/tikkrapp/injector.svg?branch=master)](https://travis-ci.com/tikkrapp/injector) 2 | 3 | Injector is a simple dependency injection lib for Dart. 4 | 5 | It does not replace a complex dependency injection framework like Dagger, but it provides the basics that most apps need. 6 | Feature requests are welcomed! 7 | 8 | Internally the injector is a singleton that stores instances and builders in a Map. 9 | 10 | Use `registerDependency()` to register the dependency. 11 | Never ever try to register or get dependencies without the generic type! Dart allows it, but we don't ;) 12 | 13 | All instances are lazy loaded, meaning that at the time you request the dependency the instance is created. 14 | 15 | Get your dependency using `get()`. 16 | 17 | 18 | 19 | ## Usage 20 | 21 | A simple usage example: 22 | 23 | // Register a dependency (Every time a new instance) 24 | injector.registerDependency(() { 25 | var engine = injector.get(); 26 | var fuel = injector.get(); 27 | var driver = injector.get(); 28 | 29 | return CarImpl(engine,fuel,driver); 30 | }); 31 | 32 | // Register a singleton 33 | injector.registerSingleton(() { 34 | var engine = injector.get(); 35 | var fuel = injector.get(); 36 | var driver = injector.get(); 37 | 38 | return CarImpl(engine,fuel,driver); 39 | }); 40 | 41 | // Use custom Factories by extending [Factory]. 42 | injector.register(CustomFactory(() => Engine())); 43 | 44 | // Register your dependencies / singletons in the __main.dart__ file 45 | 46 | ## Notice 47 | 48 | If you have an issue with getting dependencies from the injector, check that imports of your dependencies classes are absolute. 49 | 50 | Good: 51 | import 'package:/some/package/.dart'; 52 | 53 | Bad: 54 | import '../../some/package/.dart'; 55 | 56 | ## Features and bugs 57 | 58 | Please file feature requests and bugs at the [issue tracker][tracker]. 59 | 60 | [tracker]: https://github.com/tappeddev/injector/issues 61 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:extra_pedantic/analysis_options.yaml 2 | linter: 3 | rules: 4 | prefer_final_parameters: false 5 | -------------------------------------------------------------------------------- /example/injector_example.dart: -------------------------------------------------------------------------------- 1 | import 'package:injector/injector.dart'; 2 | 3 | class Engine { 4 | String capacity = ""; 5 | } 6 | 7 | abstract class Car { 8 | bool drive(); 9 | 10 | bool stop(); 11 | } 12 | 13 | class CarImpl extends Car { 14 | final Engine engine; 15 | 16 | CarImpl({required this.engine}); 17 | 18 | @override 19 | bool drive() { 20 | return true; 21 | } 22 | 23 | @override 24 | bool stop() { 25 | return true; 26 | } 27 | } 28 | 29 | abstract class Database { 30 | void add(String text); 31 | 32 | void remove(int id); 33 | } 34 | 35 | class TikkrDatabase extends Database { 36 | TikkrDatabase() { 37 | _initialize(_createTableString()); 38 | } 39 | 40 | void _initialize(String createTableString) { 41 | //Create the Database 42 | } 43 | 44 | String _createTableString() { 45 | return "CREATE TABLE USER"; 46 | } 47 | 48 | @override 49 | void add(String text) { 50 | //Do something 51 | } 52 | 53 | @override 54 | void remove(int id) { 55 | //Do something 56 | } 57 | } 58 | 59 | class CustomFactory extends Factory { 60 | CustomFactory(DependencyBuilder builder) : super(builder); 61 | 62 | @override 63 | T get instance { 64 | //Use this.builder to create your instance with custom logic. 65 | return builder(); 66 | } 67 | } 68 | 69 | void main() { 70 | // Use this static instance 71 | final injector = Injector.appInstance; 72 | 73 | // Register a dependency 74 | injector.registerDependency(() => Engine()); 75 | 76 | injector.registerDependency(() { 77 | final engine = injector.get(); 78 | return CarImpl(engine: engine); 79 | }); 80 | 81 | //Use custom Factories by extending [Factory] 82 | injector.register(CustomFactory(() => Engine())); 83 | 84 | // Maybe you want to register a class and you need it as a singleton 85 | injector.registerSingleton(() => TikkrDatabase()); 86 | } 87 | 88 | // Now you can easily get your dependencies / singletons with one line 89 | class WebView { 90 | late final Database database; 91 | late final Car customerCar; 92 | 93 | WebView() { 94 | final injector = Injector.appInstance; 95 | database = injector.get(); 96 | customerCar = injector.get(); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /injector.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /lib/injector.dart: -------------------------------------------------------------------------------- 1 | library injector; 2 | 3 | export 'src/factory/factory.dart'; 4 | export 'src/injector_base.dart'; 5 | -------------------------------------------------------------------------------- /lib/src/exception/already_defined_exception.dart: -------------------------------------------------------------------------------- 1 | /// Gets thrown when trying to register two dependencies with the same signature. 2 | /// 3 | /// For example: 4 | /// ```dart 5 | /// Injector().registerDependency((_) => FirstImplementation()); 6 | /// 7 | /// Injector().registerDependency((_) => SecondImplementation()); 8 | /// ``` 9 | class AlreadyDefinedException implements Exception { 10 | /// The Type of the already defined instance. 11 | String type; 12 | 13 | AlreadyDefinedException({required this.type}); 14 | 15 | @override 16 | String toString() => "Type \"$type\" already defined !"; 17 | } 18 | -------------------------------------------------------------------------------- /lib/src/exception/circular_dependency_exception.dart: -------------------------------------------------------------------------------- 1 | /// Gets thrown when trying to register dependencies that depends on each other 2 | /// in a circular way. 3 | /// 4 | /// The best example is: 5 | /// * A chicken depends on an egg. 6 | /// * An egg depends on a chicken. 7 | class CircularDependencyException implements Exception { 8 | /// The Type of the dependency that caused the circular dependency. 9 | String type; 10 | 11 | CircularDependencyException({required this.type}); 12 | 13 | @override 14 | String toString() => 15 | "Circular dependency detected when requesting instance of \"$type\"."; 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/exception/not_defined_exception.dart: -------------------------------------------------------------------------------- 1 | /// Gets thrown when trying to get a dependency that has not been registered yet. 2 | /// 3 | /// Some checkpoints that could cause this issue: 4 | /// * The dependency got registered with the wrong key type: 5 | /// ```dart 6 | /// Injector().registerDependency((_) => Implementation1()); 7 | /// 8 | /// Injector().getDependency(); // This throws the Exception! 9 | /// ``` 10 | /// * The dependency has not been registered at all 11 | class NotDefinedException implements Exception { 12 | /// The Type of the missing instance. 13 | String type; 14 | 15 | NotDefinedException({required this.type}); 16 | 17 | @override 18 | String toString() => "The type \"$type\" is not defined!"; 19 | } 20 | -------------------------------------------------------------------------------- /lib/src/factory/factory.dart: -------------------------------------------------------------------------------- 1 | /// Gets registered at the injector and then gets called by the injector to 2 | /// instantiate the dependency and all of its dependencies. 3 | /// 4 | /// 5 | /// Example: 6 | /// ```dart 7 | /// final myInjector = Injector(); 8 | /// 9 | /// myInjector.registerDependency(() { 10 | /// var engine = myInjector.getDependency(); 11 | /// return CarImpl(engine: engine); 12 | /// }); 13 | /// ``` 14 | typedef DependencyBuilder = T Function(); 15 | 16 | abstract class Factory { 17 | final DependencyBuilder builder; 18 | 19 | Factory(this.builder); 20 | 21 | T get instance; 22 | 23 | static Factory provider(DependencyBuilder builder) => 24 | _ProviderFactory(builder); 25 | 26 | static Factory singleton(DependencyBuilder builder) => 27 | _SingletonFactory(builder); 28 | } 29 | 30 | /// This Factory does lazy instantiation of [T] and 31 | /// always returns a new instance built by the [builder]. 32 | class _ProviderFactory implements Factory { 33 | @override 34 | DependencyBuilder builder; 35 | 36 | _ProviderFactory(this.builder); 37 | 38 | @override 39 | T get instance => builder(); 40 | } 41 | 42 | /// This Factory does lazy instantiation of [T] and 43 | /// returns the same instance when accessing [instance]. 44 | class _SingletonFactory implements Factory { 45 | @override 46 | DependencyBuilder builder; 47 | 48 | T? _value; 49 | 50 | _SingletonFactory(this.builder); 51 | 52 | @override 53 | T get instance => _value ??= builder(); 54 | } 55 | -------------------------------------------------------------------------------- /lib/src/injector_base.dart: -------------------------------------------------------------------------------- 1 | import 'exception/already_defined_exception.dart'; 2 | import 'exception/circular_dependency_exception.dart'; 3 | import 'exception/not_defined_exception.dart'; 4 | import 'factory/factory.dart'; 5 | 6 | class Injector { 7 | /// The static/single instance of the [Injector]. 8 | static final Injector appInstance = Injector(); 9 | 10 | /// Stores the all registered [Factory]. 11 | final _factoryMap = >{}; 12 | 13 | /// Registers a dependency that will be created with the provided [Factory]. 14 | /// See [Factory.provider] or [Factory.singleton]. 15 | /// You can also create your custom factory by implementing [Factory]. 16 | /// 17 | /// Overrides dependencies with the same signature when [override] is true. 18 | /// Uses [dependencyName] to differentiate between dependencies that have the 19 | /// same type. 20 | /// 21 | /// The signature of a dependency consists of [T] 22 | /// and the optional [dependencyName]. 23 | /// 24 | /// ```dart 25 | /// abstract class UserService { 26 | /// void login(String username, String password); 27 | /// } 28 | /// 29 | /// class UserServiceImpl implements UserService { 30 | /// void login(String username, String password) { 31 | /// ..... 32 | /// ..... 33 | /// } 34 | /// } 35 | /// 36 | /// injector.register(Factory.singleton(() => UserServiceImpl())); 37 | /// ``` 38 | /// Then getting the registered dependency: 39 | /// ```dart 40 | /// injector.get(); 41 | /// ``` 42 | void register(Factory factory, 43 | {bool override = false, String dependencyName = ""}) { 44 | _checkValidation(); 45 | 46 | final identity = _getIdentity(dependencyName); 47 | 48 | if (!override) { 49 | _checkForDuplicates(identity); 50 | } 51 | 52 | _factoryMap[identity] = factory; 53 | } 54 | 55 | /// Registers the [builder] with a [Factory.singleton] factory. 56 | void registerSingleton( 57 | DependencyBuilder builder, { 58 | bool override = false, 59 | String dependencyName = "", 60 | }) => 61 | this.register(Factory.singleton(builder), 62 | override: override, dependencyName: dependencyName); 63 | 64 | /// Registers the [builder] with a [Factory.provider] factory. 65 | void registerDependency( 66 | DependencyBuilder builder, { 67 | bool override = false, 68 | String dependencyName = "", 69 | }) => 70 | this.register(Factory.provider(builder), 71 | override: override, dependencyName: dependencyName); 72 | 73 | /// Whenever a factory is called to get a dependency 74 | /// the identifier of that factory is saved to this set and 75 | /// is removed when the instance is successfully created. 76 | /// 77 | /// A circular dependency is detected when the factory id was not removed 78 | /// meaning that the instance was not created 79 | /// but the same factory was called more than once 80 | final _factoryCallIds = {}; 81 | 82 | /// Returns the registered dependencies with the signature of [T] and 83 | /// the optional [dependencyName]. 84 | /// 85 | /// Throws [NotDefinedException] when the requested dependency has not been 86 | /// registered yet. 87 | /// 88 | /// Throws [CircularDependencyException] when the injector detected a circular 89 | /// dependency setup. 90 | T get({String dependencyName = ""}) { 91 | _checkValidation(); 92 | 93 | final identity = _getIdentity(dependencyName); 94 | 95 | final factory = _factoryMap[identity]; 96 | 97 | if (factory == null) { 98 | throw NotDefinedException(type: T.toString()); 99 | } 100 | 101 | final factoryId = factory.hashCode; 102 | 103 | final unique = _factoryCallIds.add(factoryId); 104 | if (!unique) { 105 | throw CircularDependencyException(type: T.toString()); 106 | } 107 | 108 | try { 109 | final instance = factory.instance as T; 110 | _factoryCallIds.remove(factoryId); 111 | return instance; 112 | // ignore: avoid_catches_without_on_clauses 113 | } catch (e) { 114 | // In case something went wrong, we have to clear the called factory list 115 | // because this will trigger a [CircularDependencyException] the next time 116 | // this factory is called again. 117 | _factoryCallIds.clear(); 118 | rethrow; 119 | } 120 | } 121 | 122 | /// Shorter syntax for [get]. 123 | T call({String dependencyName = ""}) => 124 | this.get(dependencyName: dependencyName); 125 | 126 | /// Checks if the dependency with the signature of [T] and [dependencyName] exists. 127 | bool exists({String dependencyName = ""}) { 128 | _checkValidation(); 129 | 130 | final dependencyKey = _getIdentity(dependencyName); 131 | return _factoryMap.containsKey(dependencyKey); 132 | } 133 | 134 | /// Removes the dependency with the signature of [T] and [dependencyName]. 135 | void removeByKey({String dependencyName = ""}) { 136 | _checkValidation(); 137 | 138 | final dependencyKey = _getIdentity(dependencyName); 139 | _factoryMap.remove(dependencyKey); 140 | } 141 | 142 | /// Removes all registered dependencies. 143 | void clearAll() { 144 | _factoryCallIds.clear(); 145 | _factoryMap.clear(); 146 | } 147 | 148 | // ------ 149 | // Helper 150 | // ------ 151 | 152 | /// Checks if [T] is actually set. 153 | void _checkValidation() { 154 | final type = T.toString(); 155 | 156 | if (T == dynamic) { 157 | throw Exception( 158 | "No type specified !\nCan not register dependencies for type \"$type\"", 159 | ); 160 | } 161 | } 162 | 163 | void _checkForDuplicates(String identity) { 164 | if (_factoryMap.containsKey(identity)) { 165 | throw AlreadyDefinedException(type: T.toString()); 166 | } 167 | } 168 | 169 | String _getIdentity(String dependencyName) => 170 | "$dependencyName${T.hashCode}"; 171 | } 172 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: injector 2 | description: injector is a simple to use and lightweight dependency injection library for dart 3 | version: 4.0.0 4 | homepage: https://github.com/tappeddev/injector 5 | 6 | environment: 7 | sdk: '>=2.12.0 <4.0.0' 8 | 9 | dev_dependencies: 10 | extra_pedantic: ^4.0.0 11 | test: ^1.25.8 12 | 13 | -------------------------------------------------------------------------------- /test/injector_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:injector/injector.dart'; 2 | import 'package:injector/src/exception/circular_dependency_exception.dart'; 3 | import 'package:injector/src/exception/not_defined_exception.dart'; 4 | import 'package:test/test.dart'; 5 | 6 | import 'test_classes.dart'; 7 | import 'test_classes_2.dart' as test2; 8 | 9 | void main() { 10 | final Injector injector = Injector.appInstance; 11 | 12 | setUp(() { 13 | injector.clearAll(); 14 | }); 15 | 16 | test('Register dependency / Get dependency - Test', () { 17 | injector.registerDependency(() => Fuel()); 18 | injector.registerDependency(() => Driver()); 19 | injector.registerDependency(() => Engine()); 20 | injector.registerDependency(() { 21 | final fuel = injector.get(); 22 | final driver = injector.get(); 23 | final engine = injector.get(); 24 | 25 | return CarImpl(driver: driver, engine: engine, fuel: fuel); 26 | }); 27 | 28 | final car = injector.get(); 29 | 30 | expect(car, isNotNull); 31 | expect(car.drive(), true); 32 | expect(car.stop(), true); 33 | }); 34 | 35 | test("Exception - A not registered Dependency", () { 36 | try { 37 | injector.get(); 38 | } on Exception catch (e) { 39 | expect(e, const TypeMatcher()); 40 | } 41 | }); 42 | 43 | test('Register singleton / Get singleton - Test', () { 44 | injector.registerSingleton(() => Fuel()); 45 | injector.registerSingleton(() => Driver()); 46 | injector.registerSingleton(() => Engine()); 47 | injector.registerSingleton(() { 48 | final fuel = injector.get(); 49 | final driver = injector.get(); 50 | final engine = injector.get(); 51 | return CarImpl(driver: driver, engine: engine, fuel: fuel); 52 | }); 53 | 54 | final singleTonCar1 = injector.get(); 55 | final singleTonCar2 = injector.get(); 56 | 57 | expect(singleTonCar1, same(singleTonCar2)); 58 | }); 59 | 60 | test('Register dependency calls factory function multiple times', () { 61 | var counter = 0; 62 | injector 63 | ..registerDependency(() { 64 | counter++; 65 | return Fuel(); 66 | }) 67 | ..get() 68 | ..get() 69 | ..get(); 70 | 71 | expect(counter, 3); 72 | }); 73 | 74 | test('Register two classes with the same name from different packages - Test', 75 | () { 76 | injector.registerDependency(() => Engine()); 77 | injector.registerDependency(() => test2.Engine()); 78 | 79 | final engine1 = injector.get(); 80 | final engine2 = injector.get(); 81 | 82 | expect(engine1, isNot(engine2)); 83 | }); 84 | 85 | test('Detects circular dependencies', () { 86 | injector.registerDependency(() => Engine()); 87 | 88 | injector.registerDependency(() { 89 | injector.get(); 90 | 91 | // this will trigger the cycle 92 | // since Fuel requires Driver and Driver requires Fuel 93 | injector.get(); 94 | return Fuel(); 95 | }); 96 | 97 | injector.registerDependency(() { 98 | injector.get(); 99 | injector.get(); 100 | return Driver(); 101 | }); 102 | 103 | try { 104 | injector.get(); 105 | } on Exception catch (e) { 106 | expect(e, const TypeMatcher()); 107 | } 108 | }); 109 | 110 | test("RegisterDependency with name", () { 111 | const dependencyName = "RegisterWithName"; 112 | final rawEngine = Engine(); 113 | 114 | injector.registerSingleton(() => rawEngine, 115 | dependencyName: dependencyName); 116 | 117 | final engine = injector.get(dependencyName: dependencyName); 118 | 119 | expect(engine == rawEngine, true); 120 | }); 121 | 122 | test("Register two time the same dependencies with different names", () { 123 | const dependencyName1 = "Dep1"; 124 | const dependencyName2 = "Dep2"; 125 | 126 | injector.registerDependency(() => Engine()..capacity = "1", 127 | dependencyName: dependencyName1); 128 | injector.registerDependency(() => Engine()..capacity = "2", 129 | dependencyName: dependencyName2); 130 | 131 | final engine1 = injector.get(dependencyName: dependencyName1); 132 | final engine2 = injector.get(dependencyName: dependencyName2); 133 | 134 | expect(engine1.capacity, "1"); 135 | expect(engine2.capacity, "2"); 136 | }); 137 | 138 | test("override a dependency", () { 139 | injector.registerDependency(() => Engine()..capacity = "1"); 140 | 141 | injector.registerDependency( 142 | () => Engine()..capacity = "2", 143 | override: true, 144 | ); 145 | 146 | final engine = injector.get(); 147 | 148 | expect(engine.capacity, "2"); 149 | }); 150 | 151 | test("resets circular detection when get call fails", () { 152 | var didThrow = false; 153 | 154 | injector.registerDependency(() { 155 | if (!didThrow) { 156 | didThrow = true; 157 | throw Exception("ups"); 158 | } 159 | return Engine(); 160 | }); 161 | 162 | // This first call will throw an exception and therefore 163 | // in that case we have to reset the called factories to ensure that 164 | // our circular dependency injection will not be triggered in the second call. 165 | expect( 166 | () => injector.get(), 167 | throwsA(isA()), 168 | ); 169 | 170 | // If this call works, we are save ✅ 171 | final engine = injector.get(); 172 | 173 | expect(engine, isNotNull); 174 | }); 175 | } 176 | -------------------------------------------------------------------------------- /test/test_classes.dart: -------------------------------------------------------------------------------- 1 | class Engine { 2 | String capacity = ""; 3 | } 4 | 5 | class Fuel { 6 | int octane = 95; 7 | } 8 | 9 | class Driver { 10 | String name = "Max"; 11 | } 12 | 13 | abstract class Car { 14 | bool drive(); 15 | 16 | bool stop(); 17 | } 18 | 19 | class CarImpl extends Car { 20 | final Engine engine; 21 | final Fuel fuel; 22 | final Driver driver; 23 | 24 | CarImpl({required this.engine, required this.fuel, required this.driver}); 25 | 26 | @override 27 | bool drive() { 28 | return true; 29 | } 30 | 31 | @override 32 | bool stop() { 33 | return true; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /test/test_classes_2.dart: -------------------------------------------------------------------------------- 1 | class Engine { 2 | String capacity = ""; 3 | } 4 | 5 | class Fuel { 6 | int octane = 95; 7 | } 8 | 9 | class Driver { 10 | String name = "Peter"; 11 | } 12 | --------------------------------------------------------------------------------