[−][src]Attribute Macro contraband_codegen::module
#[module]
Creates a module.
Syntax: #[module]
Example
use contraband::core::ContrabandApp; use contraband::module; use contraband::{Injectable, controller}; use actix_web::HttpResponse; #[derive(Clone, Injectable)] struct HelloController; #[controller] impl HelloController { #[get] async fn hello_world(self) -> HttpResponse { HttpResponse::Ok().body("Hello world!") } } #[module] #[controller(HelloController)] struct AppModule; #[contraband::main] async fn main() -> std::io::Result<()> { ContrabandApp::new() .start::<AppModule>() .await }
Providers
In order to inject a dependency into our different structures we need to register it as a provider.
Example
use contraband::core::ContrabandApp; use contraband::module; use contraband::{Injectable, controller}; use actix_web::HttpResponse; #[derive(Clone, Injectable)] struct HelloService; impl HelloService { fn get_hello<'a>(&self) -> &'a str { "Hello world!" } } #[derive(Clone, Injectable)] struct HelloController { hello_service: std::sync::Arc<HelloService> } #[controller] impl HelloController { #[get] async fn hello_world(self) -> HttpResponse { let ret = self.hello_service.get_hello(); HttpResponse::Ok().body(ret) } } #[module] #[controller(HelloController)] #[provider(HelloService)] struct AppModule; #[contraband::main] async fn main() -> std::io::Result<()> { ContrabandApp::new() .start::<AppModule>() .await }
Exporting and importing
Modules can be imported in order to share logic, such as database connection pools or database repositories.
In order to use a provider from another module it first needs to be exported, using the
export
-attribute. After which it can be imported in any other module using import
.
Example
use contraband::core::ContrabandApp; use contraband::module; use contraband::{Injectable, controller}; use actix_web::HttpResponse; #[derive(Clone, Injectable)] struct HelloService; impl HelloService { fn get_hello<'a>(&self) -> &'a str { "Hello world!" } } #[module] #[export(HelloService)] #[provider(HelloService)] struct HelloModule; #[derive(Clone, Injectable)] struct HelloController { hello_service: std::sync::Arc<HelloService> } #[controller] impl HelloController { #[get] async fn hello_world(self) -> HttpResponse { let ret = self.hello_service.get_hello(); HttpResponse::Ok().body(ret) } } #[module] #[controller(HelloController)] #[import(HelloModule)] struct AppModule; #[contraband::main] async fn main() -> std::io::Result<()> { ContrabandApp::new() .start::<AppModule>() .await }