I have an interface IRofl
with an implementation called DefaultRofl
with the following constructor signature:
public DefaultRofl(ICanHasCheezburger cheez)
ICanHasCheezburger
has several implementations, of which I need to resolve more than one through the IoC container, and I thought named registrations were the correct way for this.
Let's say I have two pre-created instances and want one to be the default registration, the other one named:
container.Register<ICanHasCheezburger>(cheez1);
container.Register<ICanHasCheezburger>(cheez2, "x2");
Now I need to specify that for DefaultRofl
, the "x2" registration should be resolved - and this is where I'm stuck. I know Autofac can do this, but I can't find a way with TinyIoC.
I would have expected the way to do this to be
container.Register<IRofl, DefaultRofl>().UsingConstructor(() => new DefaultRofl(container.Resolve<ICanHasCheezburger>("x2")));
but as it turns out (and I even sort of understand why), the ICanHasCheezburger
constructor parameter is just a dummy and not actually evaluated. This means the name is ignored as well, and the default registration for the interface is resolved - but this is cheez1
, which I don't want to use here.
Actually, in one more case of Jeff Atwood's rubber duck problem solving, I just kind of figured it out:
container.Register<IRofl>((c, p) => new DefaultRofl(container.Resolve<ICanHasCheezburger>("x2")));
does the trick. However, if I had more constructor arguments, I'd have to explicitly state all the container.Resolve() calls, right? Steven? ;-)
If you use named registrations then the only three ways to retrieve them are either using the Resolve overload you have there (that takes the name), using ResolveAll manually or to take a dependency of IEnumerable which will give you all the named registrations of Foo.