anthill-service-system

Rust runtime service system manager with di integration

Example

```rust use std::sync::Arc;

use anthilldi::{ DependencyContext, Constructor, types::BuildDependencyResult, }; use asynctrait::async_trait; use tokio::{ sync::{ RwLock, oneshot::{ self, Sender, Receiver, } }, };

use anthillservicesystem::{ ApplicationBuilder, Startup, configs::CoreConfig, service::{ HostedServiceConstructor, BackgroundService }, ApplicationLifeTime, extensions::AddBackgroundServiceStrategy, };

struct TestBackgroundService1 { ctx: DependencyContext, }

[async_trait]

impl HostedServiceConstructor for TestBackgroundService1 { async fn ctor(applicationlife_time: Arc>, ctx: DependencyContext) -> BuildDependencyResult { Ok(Self { ctx }) } }

[async_trait]

impl BackgroundService for TestBackgroundService1 { async fn execute(&mut self) { let sender = self.ctx.getsingleton::>>().await.unwrap() .write().await .take().unwrap(); sender.send("test".tostring()).unwrap(); } }

struct TestBackgroundService2 { applicationlifetime: Arc>, ctx: DependencyContext, }

[async_trait]

impl HostedServiceConstructor for TestBackgroundService2 { async fn ctor(applicationlifetime: Arc>, ctx: DependencyContext) -> BuildDependencyResult { Ok(Self { applicationlifetime, ctx, }) } }

[async_trait]

impl BackgroundService for TestBackgroundService2 { async fn execute(&mut self) { let receiver = self.ctx.getsingleton::>>().await.unwrap().write().await.take().unwrap(); asserteq!("test".tostring(), receiver.await.unwrap()); self.applicationlife_time.write().await.running.cancel().await; } }

struct TestStartup {}

[async_trait]

impl Constructor for TestStartup { async fn ctor(_ctx: DependencyContext) -> BuildDependencyResult { Ok(Self {}) } }

[async_trait]

impl Startup for TestStartup { async fn configuresystem(&mut self, _dependencycontext: &mut DependencyContext, coreconfig: Arc>) {

}

async fn configure_dependency(&mut self, dependency_context: &mut DependencyContext) {
    let (tx, rx) = oneshot::channel::<String>();

    dependency_context.add_singleton_instance(Some(tx)).await.unwrap();
    dependency_context.add_singleton_instance(Some(rx)).await.unwrap();

    dependency_context.add_background_service::<TestBackgroundService1>().await;
    dependency_context.add_background_service::<TestBackgroundService2>().await;
}

}

fn main() { let rt = Runtime::new().unwrap();

rt.block_on(async {
    ApplicationBuilder::new().await
        .with_startup::<TestStartup>().await
        .build().await
        .run().await
        .unwrap();
});

}

```

Refs: