Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Shaku can be used without dyn traits #8

Closed
AzureMarker opened this issue Jan 10, 2021 · 0 comments
Closed

Shaku can be used without dyn traits #8

AzureMarker opened this issue Jan 10, 2021 · 0 comments

Comments

@AzureMarker
Copy link

AzureMarker commented Jan 10, 2021

Hello there! I'm the shaku dev, and noticed this new DI library. It looks pretty interesting. I especially like the various levels of scope available.

I noticed that under "Can be used without dyn traits" you list shaku as "No". In fact, shaku can be used without using trait objects as dependencies. It does require a manual implementation of Component (or Provider), but see the following example:

use shaku::{module, Component, HasComponent, Interface, Module, ModuleBuildContext};
use std::sync::Arc;

trait Service: Interface {}

// Just a normal struct, no associated trait
struct Dependency;

// A manual impl of Component is necessary because the derive automatically assumes
// the interface is a trait. This restriction could be relaxed in a future release, such that
// #[derive(Component)] + #[shaku(interface = Self)] works.
impl<M: Module> Component<M> for Dependency {
    type Interface = Self;
    type Parameters = ();

    fn build(_: &mut ModuleBuildContext<M>, _: Self::Parameters) -> Box<Self::Interface> {
        Box::new(Self)
    }
}

#[derive(Component)]
#[shaku(interface = Service)]
struct ServiceImpl {
    // Notice that there is no `dyn` here!
    #[shaku(inject)]
    dependency: Arc<Dependency>,
}

impl Service for ServiceImpl {}

module! {
    TestModule {
        components = [Dependency, ServiceImpl],
        providers = []
    }
}

fn main() {
    let module = TestModule::builder().build();

    let service: &dyn Service = module.resolve_ref();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant