具有构造函数的Autofac寄存器类型

时间:2017-09-22 14:09:43

标签: c# autofac asp.net-core-2.0

我上课了:

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;
  }
}

其中IOptionsMicrosoft.Extensions.Options类型,ILoggerMicrosoft.Extensions.Logging类型。如何在Autofac容器中使用参数注册此类型?我尝试过类似的东西:

var container = new ContainerBuilder();
container.Populate(services);
container.RegisterType<FunctionExtender>()
                .WithParameter(new TypedParameter(typeof(IOptions<Settings>), ???));

但我不知道该传递什么作为第二个论点。

1 个答案:

答案 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();
}