简体   繁体   中英

DryIoc resolve with a func

I'm trying to have objects being resolved as the result of Func<> . But I don't find how to do it.

For instance, here I have a variable (function argument) lazyInt (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 ServiceInfo.Of , etc. but with no success for the time being. How can it be done?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM