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

RecursiveLocateException with factory injection #307

Open
mythteria opened this issue Jan 27, 2023 · 1 comment
Open

RecursiveLocateException with factory injection #307

mythteria opened this issue Jan 27, 2023 · 1 comment

Comments

@mythteria
Copy link

Hi! I am migrating from autofac to grace ioc and ran into an issue. Suppose such a structure (simplified):

class AService
{
    private readonly Func<ADependency> _func;

    public AService(Func<ADependency> func) =>
        _func = func;

    public ADependency GetDependency() =>
        _func();
}

class ADependency
{
    public ADependency(AService a)
    {
    }
}

Autofac registration works fine:

var autofacContainerBuilder = new ContainerBuilder();
autofacContainerBuilder.RegisterType<ADependency>();
autofacContainerBuilder.RegisterType<AService>();
var autofacContainer = autofacContainerBuilder.Build();
var s1 = autofacContainer.Resolve<AService>();

Unfortunately, when i port it to grace, i got a RecursiveLocateException:

var graceContainer = new DependencyInjectionContainer();
graceContainer.Configure(c =>
{
    c.Export<ADependency>();
    c.Export<AService>(); // throws!
    // c.ExportFactory<IExportLocatorScope, AService>(scope => new AService(scope.Locate<Func<ADependency>>())); // work
});
var s2 = graceContainer.Locate<AService>();

I found a workaround (commented), but it looks rather ugly. Is there a more elegant way to solve this problem?

@Lex45x
Copy link
Contributor

Lex45x commented Aug 14, 2023

Hi! I hope this issue is still relevant.

From the example you've provided, it seems like Grace is trying to build a dependency graph based on the constructor parameters but it encounters circular dependencies.
Autofac works in a completely different way under the hood and so you are not facing this kind of problem with it.
Workaround is functioning because you are giving direct instructions on how the AService factory should work. So, Grace is not trying to build it for you.

If you can provide a more detailed explanation of the behavior you want to achieve I could help you to get around it.

Do you need any of those services to be a singleton? Or do you expect Each call to GetDependency to create new instances of ADependency together with AService?

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

2 participants