Lazy Resolution with Func<TService>



In some of my classes I like to delay the loading of dependencies for as long as possible, and I do this by accepting a Func<TService> as a ctor parameter rather than an instance of TService.

I was wondering whether it would be possible to add the ability to resolve a Func<TService> from a container even when I've only registered TService. Since you know how to instantiate TService, if I ask for a Func<TService> then you should be able to hand me a function that wraps up the Func<Container, TService> I've already given you, automatically passing in "this" as the parameter.

Then this sort of thing would be possible:

interface IBar { ... }
class Foo
    public Foo(Func<IBar> barFactory) { ... }

builder.Register<IBar>(c => new Bar());
builder.Register<IFoo>(c => new Foo(c.Resolve<Func<IBar>>()));

The container would resolve Func<IBar> by returning a function that resolves IBar, passing itself into "c".

Does that make sense? I really think that would be a killer feature. I don't know if other IoC containers do this.

Closed Mar 15, 2009 at 4:35 AM by


dcazzulino wrote Feb 26, 2009 at 5:56 PM

Sounds like a very cool feature indeed Matt!


dcazzulino wrote Feb 26, 2009 at 7:35 PM

This gets tricky with ctor arguments:

builder.Register((c, s) => new Bar(s));
builder.Register(c => new Foo(c.Resolve>("bar")));

Trickier in the presence of container hierarchies (i.e. the container used to partially apply the (c, s) => new Bar(s) lambda so that we can register it as a Func rather than a Func which it actually is, needs to change depending on the container where it's being resolved)...

Would love to figure it out anyway :)

mabster wrote Feb 26, 2009 at 11:46 PM

Yeah I guess if you do this:

builder.Register((c, s) => new Bar(s));

... then you should only be allowed to resolve a Func. I don't fully understand container hierarchies so I can't comment on that side of it. I hope you figure it out anyway! :)

dcazzulino wrote Mar 15, 2009 at 4:33 AM

Implemented as LazyResolve :))