2

Does anybody know what's missing to make this test work? It's a pitty that it doesn't work out of the box.

class A { }

class B { public B(A a) { } }

class C { public C(B b) { } }

[Test]
public void SuperFactoryResolutionTest()
{
    var builder = new ContainerBuilder();            
    builder.RegisterType<B>();
    builder.RegisterType<C>();

    using (var container = builder.Build())
    {
        Assert.DoesNotThrow(() =>
        {
            var factory = container.Resolve<Func<A, C>>();
            var x = factory(new A());
        });
    }
}
Marko
  • 5,437
  • 4
  • 28
  • 47
  • I'm not clear on what your goal is. Why don't you register `A` and then use the container to get an instance of `C`? – Jeff Ogata Mar 08 '13 at 19:05
  • In my scenario A is an instance of TcpClient returned by the TcpListener when client is connected... – Marko Mar 08 '13 at 19:08
  • Why not add a constructor `public C(A a) : this(new B(a)) { }` - this makes it clear how to construct a `C` given an `A`. – default.kramer Mar 11 '13 at 01:15

1 Answers1

1

No this is not supported by Autofac.

You can only pass direct dependencies when calling Resolve. So you cannot ad-hoc specify dependencies deep down in the hierarchy chain.

Anyway this is against the inversion of control principle: C should only know about B and should not know that somewhere an A is used by B. So when you ask for a C you also should not tell which A to use.

However you can achieve somewhat similar with manually building the resolution chain:

This is the closest what you can get:

var intermediateFactory = container.Resolve<Func<B,C>>();
Func<A, C> factory = 
    a => intermediateFactory(container.Resolve<B>(TypedParameter.From(a)));
var x = factory(new A());
nemesv
  • 138,284
  • 16
  • 416
  • 359