Search code examples
c#dependency-injectionautofac

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()));
}

Solution

  • 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.