[英]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 但出现错误
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)'.
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.