Vincent
Vincent

Reputation: 1151

Supply typed parameter to nested dependencies in Autofac

I was under the impression that the TypedParameter could be used to supply values during resolution in Autofac.

However, it seems that these parameters are used on the explicit type being resolved only, and does not propagate down the dependency chain.

Is there a way to accomplish this?

public interface IDepA { }

public interface IDepB { }

public interface IDepC { }

public class DepA : IDepA
{
    public DepA(IDepB depB) { }

}

public class DepB : IDepB
{
    public DepB(IDepC depC) { }
}

public class DepC : IDepC { }

[TestMethod]
public void AutofacResolutionTest()
{
    var builder = new ContainerBuilder();

    builder.RegisterType<DepA>().As<IDepA>();
    builder.RegisterType<DepB>().As<IDepB>();

    var container = builder.Build();
    // Works
    var b = container.Resolve<IDepB>(new TypedParameter(typeof(IDepC), new DepC()));
    // Does not work
    var a = container.Resolve<IDepA>(new TypedParameter(typeof(IDepC), new DepC()));
}

Upvotes: 2

Views: 271

Answers (1)

Travis Illig
Travis Illig

Reputation: 23924

Short answer: You can't pass a parameter to something in the middle of a resolve chain.

This is an FAQ in the Autofac docs.

Upvotes: 1

Related Questions