HampusMat / Syrette

The convenient dependency injection library for Rust. Mirror of https://git.hampusmat.com/syrette
https://git.hampusmat.com/syrette
Apache License 2.0
20 stars 3 forks source link

Example prevent-circular: Cannot resolve binding #1

Closed dotai2012 closed 2 years ago

dotai2012 commented 2 years ago

Version: 0.4.1 Problem:

Error: BindingResolveFailed { reason: ResolveFailed { reason: BindingResolveFailed { reason: ResolveFailed { reason: BindingResolveFailed { reason: DetectedCircular { dependency_history: DependencyHistory { inner: ["creditor::Foo", "creditor::Bar", "creditor::Foo"] } }, interface: "creditor::Foo" }, affected: "creditor::Bar" }, interface: "creditor::Bar" }, affected: "creditor::Foo" }, interface: "creditor::Foo" }

How to reproduce: This is the code I copied exactly from the example (https://git.hampusmat.com/syrette/tree/examples/prevent-circular)

#![deny(clippy::all)]
#![deny(clippy::pedantic)]
#![allow(clippy::disallowed_names)]
use std::error::Error;

use syrette::di_container::blocking::prelude::*;
use syrette::injectable;
use syrette::ptr::TransientPtr;

struct Foo
{
    bar: TransientPtr<Bar>,
}

#[injectable]
impl Foo
{
    fn new(bar: TransientPtr<Bar>) -> Self
    {
        Self { bar }
    }
}

struct Bar
{
    foo: TransientPtr<Foo>,
}

#[injectable]
impl Bar
{
    fn new(foo: TransientPtr<Foo>) -> Self
    {
        Self { foo }
    }
}

fn main() -> Result<(), anyhow::Error>
{
    let mut di_container = DIContainer::new();

    di_container.bind::<Foo>().to::<Foo>()?;
    di_container.bind::<Bar>().to::<Bar>()?;

    let foo = di_container.get::<Foo>()?.transient()?;

    Ok(())
}
HampusMat commented 2 years ago

This is the expected behaviour of this example. Should i maybe add comments to explain it?

dotai2012 commented 2 years ago

Oh, I see, so it's expected, I think we can add a comment in the code 😅

Btw, how can I bind Bar to Bar (without a trait)

Something like:

struct Bar
{}

#[injectable]
impl Bar
{
    fn new() -> Self
    {
        Self { }
    }
}

fn main() -> Result<(), Box<dyn Error>>
{
    let mut di_container = DIContainer::new();

    di_container.bind::<Bar>().to::<Bar>()?;

    let bar = di_container.get::<Bar>()?.transient()?;

    Ok(())
}

I got an error:

Error: CastFailed { interface: "creditor::Bar", binding_kind: "transient" }

Or do I have to use the factory feature?

HampusMat commented 2 years ago

I honestly haven't though much about that use case. Using a trait should be preferred in my opinion. But if you for any reason would want to, you could use a default factory

dotai2012 commented 2 years ago

So my codebase has a global Config struct -> it doesn't have any methods (so no trait)

Other services will use that global config

This workflow is very easy to do in Go (Uber Fx or Google wire)

Could it be achievable without using the factory? (because of Rust nightly)

HampusMat commented 2 years ago

I realize now that it actually should be possible to bind a struct to itself. So i have no idea why it doesn't work. I will look into it a bit later today.

HampusMat commented 2 years ago

Basically what Syrette does deep down is it downcasts types using the downcast methods of either Box, Rc or Arc. In this case it would be Box.

And the downcast method of Box is basically:

if self.is::<T>() {
    unsafe {
        let (raw, alloc): (*mut dyn Any, _) =
            Box::into_raw_with_allocator(self);

        Ok(Box::from_raw_in(raw as *mut T, alloc))
    }
}
else {
    Err(self)
}

So it would maybe be if self.is::<T>() returns false. But that makes no sense as it is literally the same type.

But as i said, i will look into this later. I just wanted to quickly throw this out there.

HampusMat commented 2 years ago

I found the problem and fixed it in e282375de4ba75c69f7d619fc33c6250f6caba18.

It was because no interface was being declared. The injectable attribute macro declares the interface with the declare_interface macro when a interface argument is given to it. So because no interface argument was given, it didn't do that. So i made it by default declare the concrete type as the interface when no interface argument is given.

HampusMat commented 2 years ago

Oh, and i added some comments to the prevent-circular example in 488faf96336711a527a3610c728a2409087b69fa.

HampusMat commented 2 years ago

Thank you so much for the help! :)

dotai2012 commented 2 years ago

Thank you so much @HampusMat

This is the best DI lib. I've already starred your repo

dotai2012 commented 2 years ago

Btw, I think we also need to update:

https://github.com/HampusMat/Syrette/blob/3c993aa73c93f0fe335ced78d9709b39cdbd1935/src/di_container/asynchronous/mod.rs#L249

HampusMat commented 2 years ago

Btw, I think we also need to update:

https://github.com/HampusMat/Syrette/blob/3c993aa73c93f0fe335ced78d9709b39cdbd1935/src/di_container/asynchronous/mod.rs#L249

Why exactly? I can't see how that line would cause any problems.

dotai2012 commented 2 years ago

Yes, I think right now we point to a struct directly, but the param requires Send + Sync

image

File to reproduce:

async.zip