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

Func<> with arguments #666

Open
Griboedoff opened this issue Nov 13, 2024 · 5 comments
Open

Func<> with arguments #666

Griboedoff opened this issue Nov 13, 2024 · 5 comments

Comments

@Griboedoff
Copy link

net6, DryIoc 5.4.3

Hi!

I can't find the way to reuse depencency A when using creation Func for B.

My use case is this:

  • A is other service client that has some heavy initialization logic in constructor and it will be ok to register A as singletone.
  • B is client wrapper with string arg in constructor that specify user for A.

currently DryIoc calls A constructor every time getB called.

Is there a way to reuse A instance in creating B?

P.S. I saw docs for Func wrapper but asResolutionCall does not do the job.

using DryIoc;

var dc = new Container(
    r => r
        .WithMicrosoftDependencyInjectionRules()
        .WithDefaultIfAlreadyRegistered(IfAlreadyRegistered.Throw)
        .WithConcreteTypeDynamicRegistrations()
        .WithIgnoringReuseForFuncWithArgs());
dc.Register<A>(reuse: Reuse.Singleton);
dc.Register<B>();
var getB = dc.Resolve<Func<string, B>>();
getB("1");
getB("2");

class A
{
    public A()
        => Console.WriteLine("A created");
}

class B
{
    public B(A a, string s) {}
}
@dadhi
Copy link
Owner

dadhi commented Nov 13, 2024

@Griboedoff Does it work if you remove .WithIgnoringReuseForFuncWithArgs()?

@Griboedoff
Copy link
Author

It will.

But for some legacy reasons we have .WithDefaultReuse(Reuse.Singleton) on whole container
Is there any way to achieve same behaviour?

@dadhi
Copy link
Owner

dadhi commented Nov 13, 2024

I need to think about that.
Problem is, I cannot say if a scoped service or singleton or its dependency still need the passed argument.
Container can tell that for sure only when traversing to the last dependency in a chain. By this moment, it is already too late to keep the reuse.
Another approach may be to mark a specific dependency with reuse to be omitted by this rule. More configs to the God of configs :)

@Griboedoff
Copy link
Author

Okay, thanks

For now I think the best solution is explicit factory for class B which curries all arguments except string from B constructor

@dadhi
Copy link
Owner

dadhi commented Nov 14, 2024

But let keep this issue open for now. It is also an interesting number of issue.

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