//! A simple example of using shaku without derives or macros. //! This is similar to what the derives and macros in the simple_with_macros //! example expand to. use shaku::{ Component, HasComponent, HasProvider, Interface, Module, ModuleBuildContext, ModuleBuilder, Provider, ProviderFn, }; use std::error::Error; use std::fmt::Debug; use std::sync::Arc; // Traits trait SimpleDependency: Interface + Debug {} trait SimpleService: Debug {} // Implementations #[derive(Debug)] struct SimpleDependencyImpl { #[allow(dead_code)] value: String, } impl SimpleDependency for SimpleDependencyImpl {} impl Component for SimpleDependencyImpl { type Interface = dyn SimpleDependency; type Parameters = SimpleDependencyImplParameters; fn build(_: &mut ModuleBuildContext, params: Self::Parameters) -> Box { Box::new(Self { value: params.value, }) } } #[derive(Default)] struct SimpleDependencyImplParameters { value: String, } #[derive(Debug)] struct SimpleServiceImpl { #[allow(dead_code)] dependency: Arc, } impl SimpleService for SimpleServiceImpl {} impl> Provider for SimpleServiceImpl { type Interface = dyn SimpleService; fn provide(module: &M) -> Result, Box> { Ok(Box::new(Self { dependency: module.resolve(), })) } } // Module struct SimpleModule { simple_dependency: Arc, simple_service: Arc>, } impl Module for SimpleModule { type Submodules = (); fn build(mut context: ModuleBuildContext) -> Self { Self { simple_dependency: Self::build_component(&mut context), simple_service: context.provider_fn::(), } } } impl HasComponent for SimpleModule { fn build_component(context: &mut ModuleBuildContext) -> Arc { context.build_component::() } fn resolve(&self) -> Arc { Arc::clone(&self.simple_dependency) } fn resolve_ref(&self) -> &dyn SimpleDependency { Arc::as_ref(&self.simple_dependency) } } impl HasProvider for SimpleModule { fn provide(&self) -> Result, Box> { (self.simple_service)(self) } } //noinspection DuplicatedCode fn main() { let dependency_params = SimpleDependencyImplParameters { value: "foo".to_string(), }; let module = ModuleBuilder::::with_submodules(()) .with_component_parameters::(dependency_params) .build(); let dependency: &dyn SimpleDependency = module.resolve_ref(); let service: Box = module.provide().unwrap(); println!("{:?}", dependency); println!("{:?}", service); }