Singleton Macro
Spring Framework-inspired dependency injection and singleton pattern macros for Rust backend services.
Features
- 🚀 Zero-boilerplate singleton pattern with automatic dependency injection
- 🔄 Spring-like DI:
Arc<T>fields are automatically injected via ServiceLocator - 📦 Service & Repository macros for clean architecture
- 🛡️ Thread-safe using
ArcandOnceCell - 🎯 MongoDB & Redis integration helpers
- ⚡ Compile-time dependency resolution with
inventorycrate
Quick Start
Add to your Cargo.toml:
[]
= "0.1.0"
= "1.0"
= "0.3"
= "0.1"
# Optional: for MongoDB & Redis integration
= "3.2"
= "0.31"
Usage
Basic Service
use service;
use Arc;
// Usage
let service = instance;
Repository with MongoDB & Redis
use repository;
use Arc;
Service Registry Setup
use crateServiceLocator;
async
Generated Code
The #[service] macro generates:
The #[repository] macro additionally generates:
Dependency Injection Rules
| Field Type | Field Name | Injection |
|---|---|---|
Arc<T> |
any | ServiceLocator::get::<T>() |
| any | db, database |
ServiceLocator::get::<Database>() |
| any | redis, cache |
ServiceLocator::get::<RedisClient>() |
| other | any | Default::default() |
Registry System
Services and repositories are automatically registered:
#[service]→{name}#[repository]→{name}
// Registered as "auth"
// Registered as "user"
Architecture Example
// 1. Repository Layer
// 2. Service Layer
// 3. Application Layer
Best Practices
✅ Do
- Use clear layered architecture (Repository → Service → Controller)
- Register core dependencies (Database, Redis) before using services
- Keep services focused on single responsibilities
❌ Avoid
- Circular dependencies (A → B → A will panic at runtime)
- Direct repository access from controllers (use services)
- Mixing business logic in repositories
Error Handling
Common issues and solutions:
// ❌ Circular dependency
// Runtime panic!
// ✅ Proper layering
Author
Janghoon Park ceo@dataengine.co.kr
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under either of
- Apache License, Version 2.0, (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
at your option.
Copyright (c) 2025 Janghoon Park ceo@dataengine.co.kr