I had to write a test where I need to inject a configuration dependency through IOptions<>
. So far I had been using Autofac in my tests, so I wouldnāt go through all the trouble to get IOptions<>
working inside Autofac (especially when Microsoft DI offers the convenient AddOptions<>
and Configure<>
methods).
Luckily it is not that hard to bring the 2 DI containers together. Here is the code I used inside my tests:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var configuration = new ConfigurationBuilder() | |
.AddJsonFile("appsettings.json", optional: true) | |
.Build(); | |
//Initialize Microsoft DI | |
var serviceCollection = new ServiceCollection(); | |
serviceCollection.AddOptions(); | |
serviceCollection.Configure<ExampleOptions>(configuration.GetSection("Example")); | |
//Initialize Autofac | |
var containerBuilder = new ContainerBuilder(); | |
//Link the 2 together | |
containerBuilder.Populate(serviceCollection); | |
var container = containerBuilder.Build(); |