1

I need to inject object B and C to A where object C is used by B (all objects are created in Autofac) If there will be no needs for B to use C (object C is used for storing parameters) and I could use hardcoded values I could write something like this:

     builder.RegisterType<B>().As<IB>().WithParameter("key","value");

But what should I do if parametrs are created through autofac?

     builder.RegisterType<B>().As<IB>().WithParameter("key",C.value);
Cœur
  • 37,241
  • 25
  • 195
  • 267
Anton Putov
  • 1,951
  • 8
  • 34
  • 62

1 Answers1

0

I believe this is what you are looking for

class B
{
    public B(string key, C anotherDependency)
    {
        this.Key = key;
    }

    public string Key { get; private set; }
}

class C
{
    public string Value { get { return "C.Value"; } }
}

[TestMethod]
public void test()
{
    var cb = new ContainerBuilder();

    cb.RegisterType<B>().WithParameter(
        (prop, context) => prop.Name == "key",
        (prop, context) => context.Resolve<C>().Value);

    cb.RegisterType<C>();

    var b = cb.Build().Resolve<B>();
    Assert.AreEqual("C.Value", b.Key);
}

Another way you might want to consider is this

class B
{
    public B(string key) { ... }

    public B(C c) : this(c.Value) { }
}

which means you don't need anything special in the composition root - Autofac will automatically choose the 2nd constructor (assuming C is registered and string is not).

default.kramer
  • 5,943
  • 2
  • 32
  • 50