一个依赖注入容器。
对actix的actor,支持注入依赖的对象到actor对象中。
```rust use std::{collections::HashMap, sync::Arc};
use actix::prelude::*; use beanfactory::BeanDefinition; use beanfactory::BeanFactory; use beanfactory::Inject; use beanfactory::bean;
pub struct ConfigService {
pub(crate) config_map: HashMap
impl Actor for ConfigService {
type Context=Context
pub enum ConfigCmd {
Set(Arc
pub enum ConfigResult {
None,
Value(Arc
impl Handler
fn handle(&mut self, msg: ConfigCmd, _ctx: &mut Self::Context) -> Self::Result {
match msg {
ConfigCmd::Set(key, val) => {
self.config_map.insert(key, val);
Ok(ConfigResult::None)
},
ConfigCmd::Query(key) => {
if let Some(v) = self.config_map.get(&key) {
Ok(ConfigResult::Value(v.clone()))
}
else{
Ok(ConfigResult::None)
}
},
}
}
}
pub struct ConfigApi {
pub(crate) config_service: Option
impl Inject for ConfigApi {
type Context=Context
fn inject(&mut self, factory_data: bean_factory::FactoryData, _factory: bean_factory::BeanFactory, _ctx: &mut Self::Context) {
self.config_service = factory_data.get_actor();
if self.config_service.is_some() {
println!("ConfigApi:inject success");
}
else{
println!("ConfigApi:inject none");
}
}
fn complete(&mut self, _ctx: &mut Self::Context) {
println!("ConfigApi:inject complete");
}
}
impl Actor for ConfigApi {
type Context=Context
impl Handler
fn handle(&mut self, msg: ConfigCmd, _ctx: &mut Self::Context) -> Self::Result {
let config_service = self.config_service.clone();
let fut=async {
if let Some(addr) = config_service {
println!("inject success. use inject config_service handle msg");
addr.send(msg).await?
}
else{
Err(anyhow::anyhow!("inject failed. config_service is none"))
}
}
.into_actor(self)
;//.map(|r,_act,_ctx|{r});
Box::pin(fut)
}
}
async fn main() -> anyhow::Result<()> {
let factory = BeanFactory::new();
factory.register(BeanDefinition::actorwithinjectfromdefault::