Search code examples
c#dependency-injectionautofac.net-4.8

In Autofac C# Resolve, how to pass parameter to constructor


I have an Interface with the class whose constructor takes Autofac IContainer as a parameter. How I can pass this parameter at a time to resolve this class. I have tried to use new NamedParameter but getting an error

Class

public class AppAmbientState : IAppAmbientState
{
    public IContainer ServiceContainer { get; }

    public AppAmbientState(
        IContainer container
        )
    {
        ServiceContainer = container;
    }
}

In the console app

  var appAmbientState = buildContainer.Resolve<IAppAmbientState>(new NamedParameter("IContainer", "buildContainer"));

Registration to container

 public static IContainer Configure()
    {
        ContainerBuilder builder = new ContainerBuilder();

        builder.RegisterType<AppAmbientState>().As<IAppAmbientState>().SingleInstance();

error

DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'App.ConsoleHost.AmbientState.AppAmbientState' can be invoked with the available services and parameters:
Cannot resolve parameter 'Autofac.IContainer container' of constructor 'Void .ctor(Autofac.IContainer)'.

Solution

  • You are getting error because named argument is container but IContainer is type of this argument. You can change your code to:

    var appAmbientState = buildContainer.Resolve<IAppAmbientState>(new NamedParameter("container", buildContainer));
    

    and it will work