15

Given registered services:

builder.RegisterType<Foo1>().Named<IFoo>("one").As<IFoo>();
builder.RegisterType<Foo2>().Named<IFoo>("two").As<IFoo>();
builder.RegisterType<Foo3>().Named<IFoo>("three").As<IFoo>();

Can I retrieve named implementations of IFoo interface by injecting something like Func<string, IFoo> ?

public class SomeClass(Func<string, IFoo> foo) {
    var f = foo("one");
    Debug.Assert(f is Foo1);

    var g = foo("two");
    Debug.Assert(g is Foo2);

    var h = foo("three");
    Debug.Assert(h is Foo3);
}

I know I can do it with Meta<>, but I don't want to use it.

filmor
  • 30,840
  • 6
  • 50
  • 48
ppiotrowicz
  • 4,464
  • 3
  • 32
  • 46

1 Answers1

28

You could register your own resolving delegate like this:

builder.Register<Func<string, IFoo>>(c =>
    {
        var cc = c.Resolve<IComponentContext>();
        return named => cc.ResolveNamed<IFoo>(named);
    });
Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131
  • 3
    Minor edit - the 'c' parameter is a temporary; you need to resolve IComponentContext if you want to hang onto it like this. c => { var cc = c.Resolve(); return named => cc.Resolve(named); } – Nicholas Blumhardt May 28 '10 at 22:44
  • Agreed - I'd like to find a way to make this easier to catch. – Nicholas Blumhardt May 30 '10 at 23:04
  • 1
    Why are you resolving the IComponentContext ? The parameter c is already IComponentContext. You can use it like this :builder.Register>(c => named => c.Resolve(named)); – user137348 Oct 02 '10 at 09:25
  • 2
    @user137348 - as Nicholas mentions, the 'c' context is a temporary context instance. If you "store" that context in the lambda we're registering the lambda will not work as expected. By resolving 'IComponentContext' we'll get a "real" context that can be passed around. – Peter Lillevold Oct 04 '10 at 13:58
  • Still one typo, should be c => { var cc = c.Resolve(); return named => cc.ResolveNamed(named); } – Alexey Zimarev Dec 04 '12 at 12:33
  • @AlexeyZimarev - you're right, don't know why I changed that to object :| – Peter Lillevold Dec 04 '12 at 15:40
  • @PeterLillevold thanks. you're right. removed comment to avoid confusion. – JJS Jul 31 '16 at 17:05
  • @JJS - all's well. I'll remove my comments on this too, then :) – Peter Lillevold Jul 31 '16 at 21:54