20

I'd want to ask how to create an instance of ASP.NET Core's Configuration, the same that's being created when I require it in Controller's constructor which knows about the appsettings.json file

like _config = ActivatorUtilities.CreateInstance<IConfiguration>(null);

System.InvalidOperationException: 'A suitable constructor for type 'Microsoft.Extensions.Configuration.IConfiguration' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.'

It makes sense because it is interface, but how it does work in Controller's Constructor case? and how can I create an instance of that?

I'm using MS DI

Thanks

Joelty
  • 1,751
  • 5
  • 22
  • 64

1 Answers1

33

You can create a local instance of configuration as shown below.

IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath([PATH_WHERE_appsettings.json_RESIDES])
            .AddJsonFile("appsettings.json")
            .Build();

For further information see Configuration in ASP.NET Core

Mustafa Gursel
  • 782
  • 1
  • 7
  • 16
  • 2
    It works fine but you have to manually add nugets -> `https://stackoverflow.com/questions/46843367/how-to-setbasepath-in-configurationbuilder-in-core-2-0` Anyway, any idea on how to do that via DI? – Joelty Jun 24 '19 at 08:59
  • Are you asking how you can access the IConfiguration interface without adding the NuGet packages which contain it? – Jamie Taylor Jun 24 '19 at 09:10
  • 1
    @Joelty: The beauty on dependency injection is that you don't have to care about how and where it's instantiated, you just request the interface. Rest is either configured by you (your own dependencies) or by the framework (here: ASP.NET Core and the WebHost/GenericHost builders - which can be customized of course) – Tseng Jun 24 '19 at 09:58
  • thks, it works fine... var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json"); – Marinpietri Oct 22 '20 at 20:58
  • To execute unit test the framework .net core don't provide DI, than we should create programmatically an instance of object Iconfiguration – Marinpietri Oct 22 '20 at 21:06
  • This is good, but the resulting object cannot be passed to the DI in a unit test eg using ServiceCollection: `services.AddTransient(obj)` – PandaWood Sep 16 '22 at 00:29