在 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));
它会起作用
我有一个 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));
它会起作用