pub trait ServiceToken:
Send
+ Sync
+ 'static {
type Service: ?Sized + Send + Sync + 'static;
// Provided methods
fn service_type_id() -> TypeId
where Self::Service: 'static { ... }
fn service_type_name() -> &'static str { ... }
fn token_type_name() -> &'static str { ... }
}
Expand description
Trait for service tokens that provide compile-time trait-to-implementation mapping
Service tokens are zero-sized types that act as compile-time identifiers for specific services or traits. They enable type-safe dependency resolution through semantic naming rather than concrete type dependencies.
§Design Principles
- Zero Runtime Cost: Tokens are zero-sized and only exist at compile time
- Type Safety: Prevents incorrect service resolution through type constraints
- Semantic Naming: Enables meaningful service identifiers like
EmailNotificationToken
- Trait Resolution: Allows injection of trait objects rather than concrete types
§Implementation Requirements
- Token must be a zero-sized struct
- Associated
Service
type must beSend + Sync + 'static
- Service type is typically a trait object (
dyn Trait
)
§Examples
§Basic Trait Token
use elif_core::container::ServiceToken;
trait Database: Send + Sync {}
struct DatabaseToken;
impl ServiceToken for DatabaseToken {
type Service = dyn Database;
}
§Specialized Service Token
use elif_core::container::ServiceToken;
trait CacheService: Send + Sync {
fn get(&self, key: &str) -> Option<String>;
}
struct CacheToken;
impl ServiceToken for CacheToken {
type Service = dyn CacheService;
}
struct RedisCache;
impl CacheService for RedisCache {
fn get(&self, _key: &str) -> Option<String> {
None // Mock implementation
}
}
Required Associated Types§
Provided Methods§
Sourcefn service_type_id() -> TypeIdwhere
Self::Service: 'static,
fn service_type_id() -> TypeIdwhere
Self::Service: 'static,
Get the TypeId of the service type
Used internally for service resolution and type checking. Default implementation should suffice for most use cases.
Sourcefn service_type_name() -> &'static str
fn service_type_name() -> &'static str
Get the type name of the service
Used for debugging and error messages. Default implementation should suffice for most use cases.
Sourcefn token_type_name() -> &'static str
fn token_type_name() -> &'static str
Get the token type name
Used for debugging and error messages. Default implementation should suffice for most use cases.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.