Skip to main content

ApplicationContext

Struct ApplicationContext 

Source
pub struct ApplicationContext { /* private fields */ }
Expand description

Main application context

ApplicationContext serves as the central hub for application-wide services, configuration, environment management, and integration with the IoC container. It provides a unified interface for accessing all framework services.

§Examples

use verdure_context::ApplicationContext;

let context = ApplicationContext::builder()
    .with_property("app.name", "MyApp")
    .build()
    .unwrap();

// Access configuration
let app_name = context.get_config("app.name");

// Access IoC container
let container = context.container();

Implementations§

Source§

impl ApplicationContext

Source

pub fn new() -> ApplicationContext

Creates a new application context

§Examples
use verdure_context::ApplicationContext;

let context = ApplicationContext::new();
Source

pub fn builder() -> ApplicationContextBuilder

Creates a builder for constructing an application context

§Examples
use verdure_context::ApplicationContext;

let context = ApplicationContext::builder()
    .with_property("app.version", "1.0.0")
    .build()
    .unwrap();
Source

pub fn initialize(&self) -> Result<(), ContextError>

Initializes the application context

This method initializes the IoC container and performs any other necessary initialization steps.

§Returns

Ok(()) if initialization succeeds, an error otherwise

§Examples
use verdure_context::ApplicationContext;

let context = ApplicationContext::new();
context.initialize().unwrap();
Source

pub fn get_config(&self, key: &str) -> String

Gets a configuration value by key

§Arguments
  • key - The configuration key
§Returns

The configuration value as a string, or an empty string if not found

§Examples
use verdure_context::{ApplicationContext, ConfigSource};
use std::collections::HashMap;

let mut context = ApplicationContext::new();

let mut props = HashMap::new();
props.insert("app.name".to_string(), "MyApp".to_string());
context.add_config_source(ConfigSource::Properties(props)).unwrap();

assert_eq!(context.get_config("app.name"), "MyApp");
Source

pub fn get_config_as<T>(&self, key: &str) -> Result<T, ContextError>
where T: FromStr, <T as FromStr>::Err: Display,

Gets a configuration value as a specific type

§Arguments
  • key - The configuration key
§Returns

The configuration value parsed as the requested type

§Errors

Returns an error if the key is not found or cannot be parsed as the requested type

§Examples
use verdure_context::{ApplicationContext, ConfigSource};
use std::collections::HashMap;

let mut context = ApplicationContext::new();

let mut props = HashMap::new();
props.insert("app.port".to_string(), "8080".to_string());
context.add_config_source(ConfigSource::Properties(props)).unwrap();

let port: i64 = context.get_config_as("app.port").unwrap();
assert_eq!(port, 8080);
Source

pub fn get_config_or_default(&self, key: &str, default: &str) -> String

Gets a configuration value with a default

§Arguments
  • key - The configuration key
  • default - The default value to return if key is not found
§Examples
use verdure_context::ApplicationContext;

let context = ApplicationContext::new();
let port = context.get_config_or_default("app.port", "8080");
assert_eq!(port, "8080");
Source

pub fn set_config(&self, key: &str, value: &str)

Sets a configuration property

§Arguments
  • key - The configuration key
  • value - The configuration value
§Examples
use verdure_context::ApplicationContext;

let mut context = ApplicationContext::new();
context.set_config("runtime.property", "runtime.value");

assert_eq!(context.get_config("runtime.property"), "runtime.value");

Sets a configuration property

Source

pub fn add_config_source( &self, source: ConfigSource, ) -> Result<(), ContextError>

Adds a configuration source

Source

pub fn container(&self) -> Arc<ComponentContainer>

Gets the IoC container

§Returns

A reference to the IoC container

§Examples
use verdure_context::ApplicationContext;

let context = ApplicationContext::new();
let container = context.container();
Source

pub fn config_manager(&self) -> Arc<ConfigManager>

Gets a shared reference to the ConfigManager for IoC registration

Source

pub fn get_component<T>(&self) -> Option<Arc<T>>
where T: 'static + Send + Sync,

Gets a component from the IoC container

§Returns

The requested component if found

§Examples
use verdure_context::ApplicationContext;
use std::sync::Arc;

#[derive(Debug)]
struct MyService {
    name: String,
}

let context = ApplicationContext::new();

// First register the component
let service = Arc::new(MyService {
    name: "TestService".to_string(),
});
context.container().register_component(service);

// Then retrieve it
let retrieved: Option<Arc<MyService>> = context.get_component();
assert!(retrieved.is_some());
Source

pub fn register_component(&self, instance: Arc<dyn Any + Sync + Send>)

Registers a pre-created component instance with the context container

Source

pub fn publish_event<T>(&self, event: &T)
where T: Event + 'static,

Publishes an event

§Arguments
  • event - The event to publish
§Examples
use verdure_context::{ApplicationContext, Event};
use std::any::Any;

#[derive(Debug, Clone)]
struct MyEvent {
    message: String,
}

impl Event for MyEvent {
    fn name(&self) -> &'static str { "MyEvent" }
    fn as_any(&self) -> &dyn Any { self }
    fn into_any(self: Box<Self>) -> Box<dyn Any> { self }
}

let context = ApplicationContext::new();
let event = MyEvent {
    message: "Hello, World!".to_string(),
};

context.publish_event(&event);
Source

pub fn subscribe_to_context_events<T, L>(&self, listener: L)
where T: Event + 'static, L: ContextAwareEventListener<T> + 'static,

Subscribes to events with context access

Context-aware listeners receive both the event and a reference to the ApplicationContext, allowing them to interact with the context during event handling.

§Arguments
  • listener - The context-aware event listener to register
§Examples
use verdure_context::{ApplicationContext, ContextInitializedEvent, ContextAwareEventListener};

struct StartupListener;

impl ContextAwareEventListener<ContextInitializedEvent> for StartupListener {
    fn on_context_event(&self, event: &ContextInitializedEvent, context: &ApplicationContext) {
        println!("Context initialized! App name: {}", context.get_config("app.name"));
        println!("Environment: {}", context.environment());
    }
}

let mut context = ApplicationContext::new();
context.subscribe_to_context_events(StartupListener);

Subscribes to events with context access

Source

pub fn subscribe_to_events<T, L>(&self, listener: L)
where T: Event + 'static, L: EventListener<T> + 'static,

§Arguments
  • listener - The event listener to register
§Examples
use verdure_context::{ApplicationContext, Event, EventListener};
use std::any::Any;

#[derive(Debug, Clone)]
struct TestEvent;

impl Event for TestEvent {
    fn name(&self) -> &'static str { "TestEvent" }
    fn as_any(&self) -> &dyn Any { self }
    fn into_any(self: Box<Self>) -> Box<dyn Any> { self }
}

struct TestListener;

impl EventListener<TestEvent> for TestListener {
    fn on_event(&self, _event: &TestEvent) {
        println!("Event received!");
    }
}

let mut context = ApplicationContext::new();
context.subscribe_to_events(TestListener);

Subscribes to events

Source

pub fn environment(&self) -> String

Gets environment information

§Returns

A string representing the current environment

§Examples
use verdure_context::ApplicationContext;

let context = ApplicationContext::new();
println!("Environment: {}", context.environment());

Trait Implementations§

Source§

impl Default for ApplicationContext

Source§

fn default() -> ApplicationContext

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.