簡體   English   中英

在Autofac C# Resolve中,如何將參數傳遞給構造函數

[英]In Autofac C# Resolve, how to pass parameter to constructor

我有一個 class 的接口,其構造函數將 Autofac IContainer 作為參數。 我如何一次傳遞此參數來解決此 class。我嘗試使用新的 NamedParameter 但出現錯誤

Class

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

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

在控制台應用程序中

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

注冊到容器

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

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

錯誤

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

您收到錯誤消息是因為命名參數是container ,但IContainer是此參數的類型。 您可以將代碼更改為:

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

它會起作用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM