3

I have been trying to get some dependency injection into my .net core console app as well as use an appsettings.json file.

However I can't find an example with both together.

Below is a method I have to set this up from inside my Main()

private static IContainer SetupDependencyInjection()
{
        var builder2 = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");

        var builder = new ContainerBuilder();

        builder.RegisterAssemblyTypes(
            typeof(Program).GetTypeInfo().Assembly // Console
        )
        .AsSelf()
        .AsImplementedInterfaces();

        var container = builder.Build();

        return container;
    }

You can see I have the builder2 variable to set up the config file but then I need the builder variable for the Dependency Injection.

Any ideas on this?

Cyril Durand
  • 15,834
  • 5
  • 54
  • 62
Matt
  • 487
  • 1
  • 6
  • 16

1 Answers1

4

Autofac provides a ConfigurationModule class that can be build using a Iconfiguration provided by your ConfigurationBuilder

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

// Register the ConfigurationModule with Autofac.
var module = new ConfigurationModule(config.Build());
var builder = new ContainerBuilder();
builder.RegisterModule(module);

// configure whatever you want at runtime the ContainerBuilder
builder.RegisterType<Foo>().As<IFoo>(); 

// build the container 
IContainer container = builder.Build(); 

In this case you will have both registrations configured in your autofac.json file and registrations configured in your code.

See Autofac documentation JSON/XML Configuration for more detail

Cyril Durand
  • 15,834
  • 5
  • 54
  • 62
  • Thanks @Cyril. One question. autofac.json I don't quite know what I am doing with that file as I am happy to have all the registrations inline. But where does my application.json belong? The autofac.json looks like it only contains the autofac code and not application variables. – Matt Mar 23 '17 at 20:15
  • If you are happy to have all the registrations inline why do you want to use the json configuration file ? it is an optional feature and *Autofac* doesn't need it. If you don't want it, don't configure the `ConfigurationModule` module :) – Cyril Durand Mar 23 '17 at 22:40
  • 6
    Perhaps I should have explained in the question more my apologies. I have no desire to put the autofac config in json but I want to use the appsettings.json (which is the application settings). Much like the web.config. I have seen examples of the appsettings.json being used and strongly typed etc. but not when dependency injection is also being used. I am sure it is possible but I am just missing the link in code. – Matt Mar 26 '17 at 21:16