我上课了:
public class FunctionExtender : IFunctionsExtender
{
private static IOptions<Settings> _settings;
private static ILogger<FunctionExtender> _logger;
public FunctionExtender(IOptions<Settings> settings, ILogger<FunctionExtender> logger)
{
_settings = settings;
_logger = logger;
}
}
其中IOptions
是Microsoft.Extensions.Options
类型,ILogger
是Microsoft.Extensions.Logging
类型。如何在Autofac容器中使用参数注册此类型?我尝试过类似的东西:
var container = new ContainerBuilder();
container.Populate(services);
container.RegisterType<FunctionExtender>()
.WithParameter(new TypedParameter(typeof(IOptions<Settings>), ???));
但我不知道该传递什么作为第二个论点。
答案 0 :(得分:2)
您只需将FunctionExtender
注册为IFunctionsExtender
即可。 Autofac将为您解决适当的依赖关系。它是控制反转(IoC)容器的工作之一 - 注册,解析,释放和处置。
从Autofac.Extensions.DependencyInjection Version 4.2.0
开始,这就是ASP.Net Core 2
所需的全部内容。
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc();
...
}
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<FunctionExtender>().As<IFunctionsExtender>();
}
}
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureServices(services => services.AddAutofac()) <======
.UseStartup<Startup>()
.Build();
}