Serge Adneom Serge Adneom - 1 year ago 178
C# Question

DryIoc resolve with a func

I'm trying to have objects being resolved as the result of

But I don't find how to do it.

For instance, here I have a variable (function argument)
(which could be the result of long running computation of some sort) and which result is not required before a possible later usage.

private Demo(Container c, Func<int> lazyInt) : base(c)
_container = c;
c.Register<int>(made: Made.Of(/*???*/));

I tried a bit using
, etc. but with no success for the time being.
How can it be done?

Answer Source

You need to use the RegisterDelegate instead of Made.Of to work with already created run-time delegate:

var c = new Container();

Func<int> lazyInt = () => 42;
c.RegisterDelegate(_ => lazyInt());

var shouldBe42 = c.Resolve<int>();

Made.Of is better when you can provide expression with Method call or Property access for service creation. It enables DryIoc to parse the provided expression for diagnostics and put it directly into resulting factory delegate. As you already have a delegate object, then Made.Of won't do any good for you.