[英]In Autofac C# Resolve, how to pass parameter to constructor
我有一個 class 的接口,其構造函數將 Autofac IContainer 作為參數。 我如何一次傳遞此參數來解決此 class。我嘗試使用新的 NamedParameter 但出現錯誤
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.