4 个版本
0.2.2 | 2023年11月26日 |
---|---|
0.2.1 | 2023年11月26日 |
0.2.0 | 2023年11月25日 |
0.1.0 | 2020年3月21日 |
#124 in 过程宏
每月 22 次下载
9KB
83 行代码(不包括注释)
coi-rocket
Rust 中的依赖注入
此包提供了 coi 和 rocket 之间的集成支持。它暴露了一个 inject
过程属性宏,用于生成从注册到 rocket 的 Container
中检索依赖项的代码。
示例
// What's needed for the example fn below
use rocket::{get, launch};
use rocket::serde::json::Json;
use std::sync::Arc;
// Add the `inject` attribute to the function you want to inject
// What this crate provides
#[coi_rocket::inject]
#[get("/<id>")]
fn get(
id: u64,
// Add the `inject` field attribute to each attribute you want
// injected
#[inject] service: Arc<dyn IService>
) -> Result<Json<DataDto>, ()> {
let data = service.get(id)?;
Ok(Json(DataDto::from(data)))
}
// Just data models for the above fn
use serde::Serialize;
#[derive(Serialize)]
struct DataDto {
name: String,
}
impl DataDto {
fn from(data: Data) -> Self {
Self {
name: data.name
}
}
}
// An example of what's usually needed to make effective use of this
// crate is below
use coi::Inject;
// This section shows coi being put to use
// It's very important that the version of coi and the version
// of coi-rocket used match since coi-rocket implements
// some coi traits
// Here we're marking a trait as injectable
trait IService: Inject {
fn get(&self, id: u64) -> Result<Data, ()>;
}
// And here we're marking a type that's capable of providing the
// above trait
#[derive(Inject)]
#[coi(provides dyn IService with ServiceImpl::new(repo))]
struct ServiceImpl {
// Here we're injecting a dependency. `ServiceImpl` does
// not need to know how to get this value.
#[coi(inject)]
repo: Arc<dyn IRepo>
}
// Normal impl for struct
impl ServiceImpl {
fn new(repo: Arc<dyn IRepo>) -> Self {
Self { repo }
}
}
// Normal impl of trait for struct
impl IService for ServiceImpl {
fn get(&self, id: u64) -> Result<Data, ()> {
self.repo.read_from_db(id)
}
}
// The data that will be passed between services
struct Data {
id: u64,
name: String,
}
// Here's the trait from above
trait IRepo: Inject {
fn read_from_db(&self, id: u64) -> Result<Data, ()>;
}
// And it's setup below
#[derive(Inject)]
#[coi(provides dyn IRepo with RepoImpl)]
struct RepoImpl;
impl IRepo for RepoImpl {
fn read_from_db(&self, id: u64) -> Result<Data, ()> {
Ok(Data {
id,
name: format!("{}'s name...", id)
})
}
}
#[launch]
fn rocket() -> _ {
use rocket::{routes, Rocket};
use coi::container;
// Construct your coi container with your keys and providers
// See the coi crate for more details
let container = container!{
repo => RepoImplProvider; scoped,
service => ServiceImplProvider; scoped
};
Rocket::build()
// Don't forget to manage the container so it can be used!
.manage(container)
.mount("/", routes![get])
}
查看仓库 coi-rocket-sample
以获取更复杂的示例。
许可证
根据您的选择,在 Apache 许可证 2.0 版 或 MIT 许可证 下授权。除非您明确声明,否则根据 Apache-2.0 许可证定义的任何有意提交以包含在此包中的贡献,都将按上述方式双重许可,而无需任何附加条款或条件。
SPDX-许可证-标识符: MIT 或Apache-2.0
依赖关系
~15–49MB
~797K SLoC