diff --git a/examples/Cargo.toml b/examples/Cargo.toml index 2c6ce528..e5953058 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -4,6 +4,7 @@ members = [ "cloudflare-worker", "compression", "cookie", + "dependency-injection", "error-handle", "file", "grpc", diff --git a/examples/dependency-injection/Cargo.toml b/examples/dependency-injection/Cargo.toml new file mode 100644 index 00000000..bd601239 --- /dev/null +++ b/examples/dependency-injection/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "dependency-injection" +version = "0.1.0" +edition = "2021" + +[dependencies] +xitca-web = "0.2.2" diff --git a/examples/dependency-injection/src/main.rs b/examples/dependency-injection/src/main.rs new file mode 100644 index 00000000..f4568bd5 --- /dev/null +++ b/examples/dependency-injection/src/main.rs @@ -0,0 +1,48 @@ +//! example for using trait object as application state. + +use std::sync::Arc; + +use xitca_web::{ + handler::{handler_service, state::StateRef}, + route::get, + App, +}; + +fn main() -> std::io::Result<()> { + App::new() + // use trait object as application state + .with_state(object_state()) + // extract trait object in handler + .at("/", get(handler_service(handler))) + .serve() + .bind("127.0.0.1:8080")? + .run() + .wait() +} + +// a simple trait for injecting dependent type and logic to application. +trait DI { + fn name(&self) -> &'static str; +} + +// thread safe trait object state constructor. +fn object_state() -> Arc { + // a dummy type implementing DI trait. + struct Foo; + + impl DI for Foo { + fn name(&self) -> &'static str { + "foo" + } + } + + // only this function knows the exact type implementing DI trait. + // everywhere else in the application it's only known as dyn DI trait object. + Arc::new(Foo) +} + +// StateRef extractor is able extract &dyn DI from application state. +async fn handler(StateRef(obj): StateRef<'_, dyn DI + Send + Sync>) -> String { + // get request to "/" path should return "hello foo" string response. + format!("hello {}", obj.name()) +} diff --git a/test/Cargo.toml b/test/Cargo.toml index fd965d60..215896e4 100644 --- a/test/Cargo.toml +++ b/test/Cargo.toml @@ -8,13 +8,13 @@ io-uring = ["xitca-http/io-uring", "xitca-server/io-uring"] [dependencies] xitca-client = { version = "0.1", features = ["http2", "http3", "websocket", "dangerous"] } -xitca-http = { version = "0.2", features = ["http2", "http3"] } +xitca-http = { version = "0.2.1", features = ["http2", "http3"] } xitca-codegen = "0.1" xitca-io = "0.1" xitca-server = { version = "0.1", features = ["http3"] } xitca-service = "0.1" xitca-unsafe-collection = "0.1" -xitca-web = "0.2" +xitca-web = "0.2.2" http-ws = { version = "0.2", features = ["stream"] } diff --git a/web/CHANGES.md b/web/CHANGES.md index b66e42f3..d12c6217 100644 --- a/web/CHANGES.md +++ b/web/CHANGES.md @@ -1,4 +1,6 @@ -# unreleased 0.2.2 +# unreleased + +# 0.2.2 ## Add - `StateRef` can used for extracting `?Sized` type from application state.