Net Core: access to appsettings.json values from Autofac Module

情到浓时终转凉″ 提交于 2019-12-06 02:32:48

问题


AspNet core app

1) Autofac module like that

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

2) Module from step№1 registered into Startup.cs

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

How to access to appsettings.json values from AutofacModule? I need that for create my objects inside AutofacModule and using it for DI.


回答1:


Need to change step №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));
    }

I don't know is "best practise" way or not, but it works.




回答2:


So currently trying this as well.

First thing is to get the necessary nuget packages, and add them as using statements at the top of your class.

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

In your Program.cs Main or 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();
}

This will register the configuration module into your autoFac container, after which you can then use constructor injection to pass this round...

public class YourController
{
    private readonly IContainer _config;

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

Hope that helps somewhat, if you get any further a different way then please share.



来源:https://stackoverflow.com/questions/46888812/net-core-access-to-appsettings-json-values-from-autofac-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!