简体   繁体   English

在Autofac C# Resolve中,如何将参数传递给构造函数

[英]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.我有一个 class 的接口,其构造函数将 Autofac IContainer 作为参数。 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。我尝试使用新的 NamedParameter 但出现错误

Class 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.您收到错误消息是因为命名参数是container ,但IContainer是此参数的类型。 You can change your code to:您可以将代码更改为:

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

and it will work它会起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 C# 中将类构造函数作为参数传递 - How to pass a class constructor as parameter in C# 如何从解析依赖项将参数传递给 Autofac 模块 - How to pass parameter to an Autofac Module from a resolve dependency Autofac 无法解析构造函数“Void”的参数 serviceScopeFactory - Autofac Cannot resolve parameter serviceScopeFactory of constructor 'Void Autofac:如何通过构造函数参数将实例注册为组件 - Autofac: How to pass constructor parameter for Register an Instance as a component 如何使用Autofac将参数传递给构造函数 - How can I pass a parameter to a constructor using Autofac c#autofac解决问题 - c# autofac resolve issue 如何将方法结果作为参数传递给C#中的基类构造函数? - How to pass method result as parameter to base class constructor in C#? 如何在Autofac中间接传递参数 - How to pass a parameter indirectly in Autofac 如何使用参数构造函数动态创建实例,使用autofac DI解决 - How can I create instance Dynamically with parameter constructor resolve using autofac DI 一个 class 的属性作为参数传递给另一个 class 的构造函数。 如何用 Autofac 解决这个问题? - Property of one class is passed as parameter to constructor of another class. How to resolve this with Autofac?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM