2017-10-23 2 views
3

ASPnet Kern appNet Kern: Zugriff auf appsettings.json Werte von Autofac Modul

1) Autofac Modul wie die

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

2) Module von step№1 in Startup.cs registriert

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

Zugriff auf appsettings.json Werte von AutofacModule? Ich brauche das für meine Objekte innerhalb AutofacModule erstellen und für DI verwenden.

Antwort

2

Need Schritt №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)); 
    } 

Ich weiß nicht, zu ändern ist "best practice" Art und Weise oder nicht, aber es funktioniert.

1

Also gerade dies auch versuchen.

Als Erstes müssen Sie die erforderlichen nuget-Pakete abrufen und sie als Anweisungen an der Spitze Ihrer Klasse hinzufügen.

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

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

Dadurch wird das Konfigurationsmodul in Ihrem Autofac Container registrieren, nach dem Sie dann Konstruktor Injektion können diese Runde passieren ...

Hoffe, dass hilft etwas, wenn Sie einen anderen Weg dann bitte teilen.

Verwandte Themen