get_it_injector_gen 0.7.0+1
get_it_injector_gen: ^0.7.0+1 copied to clipboard
Automate class registration for dependency injection using `get_it`, Simplify and manage dependencies effortlessly in Dart projects.
Get It Injector Generator #
Code generator for automated dependency injection with get_it
This package generates registration code for dependency injection based on annotations from get_it_injector. It eliminates the need to manually write and maintain dependency registration code.
Features #
✅ Annotation-Based - Generate code from simple class annotations
✅ Interface Registration - Automatically register implementations for their interfaces
✅ Multiple Interfaces - Support for classes implementing multiple interfaces
✅ Priority Control - Define registration order with priority annotations
✅ Grouping - Organize dependencies into logical groups
✅ Pattern Matching - Use regex patterns for bulk registration
✅ Type Safety - Generated code is fully type-safe
✅ Incremental - Only regenerates changed files
Installation #
dependencies:
get_it: ^8.0.0
get_it_injector: ^0.6.0
dev_dependencies:
get_it_injector_gen: ^0.6.0
build_runner: ^2.4.0
Quick Start #
1. Annotate Your Classes #
import 'package:get_it_injector/get_it_injector.dart';
@singleton
class ApiService {
void fetchData() => print('Fetching data...');
}
@factory
class UserRepository {
final ApiService _apiService;
UserRepository(this._apiService);
}
abstract class Logger {
void log(String message);
}
@singleton
class ConsoleLogger implements Logger {
@override
void log(String message) => print(message);
}
2. Create Setup File #
Create lib/injection.dart:
import 'package:get_it/get_it.dart';
import 'package:get_it_injector/get_it_injector.dart';
import 'injection.config.dart'; // This will be generated
final getIt = GetIt.instance;
@setup
Future<void> configureDependencies() => getIt.init();
3. Generate Code #
# Flutter projects
flutter pub run build_runner build
# Dart projects
dart run build_runner build
# Watch for changes (development)
dart run build_runner watch
4. Use in Your App #
import 'injection.dart';
void main() async {
await configureDependencies();
// Dependencies are now available
final apiService = getIt<ApiService>();
final logger = getIt<Logger>(); // Gets ConsoleLogger
runApp(MyApp());
}
Configuration Options #
Configure the generator behavior in your build.yaml file:
targets:
$default:
builders:
get_it_injector_gen:
generate_for:
- lib/**/*.dart
options:
# Basic options
auto_register: true
register_as_implementation: true
register_default: singleton # singleton, factory, lazy_singleton
# Pattern-based registration (regex)
singletons:
- ".*Service$" # Classes ending with "Service"
- ".*Repository$" # Classes ending with "Repository"
factories:
- ".*Model$" # Classes ending with "Model"
- ".*Dto$" # Classes ending with "Dto"
lazy_singletons:
- ".*Manager$" # Classes ending with "Manager"
# Control which classes to register
register:
- ".*Impl$" # Only implementation classes
do_not_register:
- ".*Test$" # Ignore test classes
- ".*Mock$" # Ignore mock classes
# Priority patterns (higher number = registered first)
priorities:
- "Core.*" # Core classes first
- ".*Service$" # Services second
- ".*Repository$" # Repositories third
# Grouping
groups:
database:
- ".*Repository$"
- ".*Dao$"
services:
- ".*Service$"
- ".*Manager$"
# Generated file options
ignore_for_file:
- "prefer_const_constructors"
- "unused_import"
Configuration Reference #
| Option | Type | Description | Default |
|---|---|---|---|
auto_register |
bool |
Register all classes automatically | false |
register_as_implementation |
bool |
Register implementations for their interfaces | false |
register_default |
string |
Default registration type | singleton |
singletons |
List<String> |
Regex patterns for singleton registration | [] |
factories |
List<String> |
Regex patterns for factory registration | [] |
lazy_singletons |
List<String> |
Regex patterns for lazy singleton registration | [] |
register |
List<String> |
Regex patterns for classes to register | [] |
do_not_register |
List<String> |
Regex patterns for classes to ignore | [] |
priorities |
List<String> |
Regex patterns for registration priority | [] |
groups |
Map<String, List<String>> |
Named groups with regex patterns | {} |
ignore_for_file |
List<String> |
Lint rules to ignore in generated files | [] |
Advanced Examples #
Interface Registration #
When register_as_implementation: true, implementations are automatically registered for their interfaces:
abstract class UserRepository {}
abstract class CacheableRepository {}
@singleton
class UserRepositoryImpl implements UserRepository, CacheableRepository {}
// Generated code:
// getIt.registerSingleton<UserRepositoryImpl>(UserRepositoryImpl());
// getIt.registerSingleton<UserRepository>(getIt<UserRepositoryImpl>());
// getIt.registerSingleton<CacheableRepository>(getIt<UserRepositoryImpl>());
Priority and Grouping #
@Priority(100)
@singleton
class CoreService {} // Registered first
@Group('database')
@singleton
class UserRepository {} // Grouped with other database classes
@mediumPriority
@singleton
class FeatureService {} // Registered with medium priority
Constructor Selection #
class DatabaseService {
DatabaseService(); // Default constructor
@use
DatabaseService.withConfig(String config); // Use this constructor
}
Performance Tips #
Optimize Build Performance #
targets:
$default:
builders:
get_it_injector_gen:
generate_for:
include:
- lib/**/*.dart
exclude:
- lib/generated/**
- lib/**/*.g.dart
- lib/**/*.freezed.dart
- test/**
Project Structure Best Practices #
- Keep setup files in a dedicated folder (e.g.,
lib/injection/) - Use meaningful names (
injection.dart,dependencies.dart) - Group related dependencies in the same files
- Separate concerns (database, services, UI, etc.)
Troubleshooting #
Common Issues #
Build fails with "Could not find import"
- Ensure all dependencies are properly imported
- Check that file paths are correct in import statements
Classes not being registered
- Verify annotations are imported from
get_it_injector - Check
build.yamlconfiguration patterns - Ensure classes are in files matched by
generate_for
Registration order issues
- Use
@Priority()annotations for explicit ordering - Check priority patterns in
build.yaml - Remember: higher priority numbers register first
Debug Generated Code #
The generated .config.dart files show exactly what's being registered:
// injection.config.dart (generated)
extension GetItInjectableX on GetIt {
Future<void> init() async {
// Registration code here
registerSingleton<ApiService>(ApiService());
registerFactory<UserRepository>(() => UserRepository(get<ApiService>()));
}
}
Related Packages #
get_it_injector- Core annotation packageget_it- Service locator for Dart and Flutter
Contributing #
We welcome contributions! Please see our Contributing Guide for details.
Issues & Support #
License #
This software is released under the Apache 2.0 license. See LICENSE for details.