简体   繁体   中英

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)'.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM