Net Core:从Autofac Module访问appsettings.json值

时间:2017-10-23 11:59:04

标签: dependency-injection .net-core autofac autofac-module

AspNet核心应用

1)Autofac模块

public class AutofacModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
      //Register my components. Need to access to appsettings.json values from here
    }
}

2)步骤1中的模块已注册到Startup.cs

public void ConfigureContainer(ContainerBuilder builder)
    {
       builder.RegisterModule(new AutofacModule());
    }

如何从appsettings.json访问AutofacModule个值?我需要在AutofacModule中创建我的对象并将其用于DI。

2 个答案:

答案 0 :(得分:2)

需要更改步骤№2

        public void ConfigureContainer(ContainerBuilder builder)
    {
        //get settigns as object from config
        var someSettings= Configuration.GetSection(typeof(SomeSettings).Name).Get<SomeSettings>();                                                    
        //put settings into module constructor 
        builder.RegisterModule(new AutofacModule(someSettings));
    }

我不知道&#34;最佳实践&#34;方式与否,但它有效。

答案 1 :(得分:1)

所以目前正在尝试这个。

首先要获得必要的nuget包,并将它们添加为类顶部的using语句。

using Microsoft.Extensions.Configuration.Json;
using Autofac;
using Autofac.Configuration;
using Autofac.Extensions.DependencyInjection;

在Program.cs Main或Startup.cs中......

public static IContainer Container { get; set; }

Main() or Startup()
{

// Add the configuration to the ConfigurationBuilder.
var config = new ConfigurationBuilder();
config.AddJsonFile("appsettings.json");

var containerBuilder = new ContainerBuilder();

// Register the ConfigurationModule with Autofac.
var configurationModule = new ConfigurationModule(config.Build());

containerBuilder.RegisterModule(configurationModule);

//register anything else you need to...

Container = containerBuilder.Build();
}

这会将配置模块注册到你的autoFac容器中,之后你可以使用构造函数注入来传递这一轮......

public class YourController
{
    private readonly IContainer _config;

    public YourController(IContainer configuration)
    {
        // Use IContainer instance
        _config = configuration;
    }

希望有所帮助,如果你有更进一步的方式,请分享。