I have a class such as this:
public class Test : ITest
{
public Test(IOptions<CustomSection> settings)
{
//do something
}
}
I would like to unit test and just maintain the dependency injection. So to accomplish this I have tried the following:
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, true)
.AddEnvironmentVariables();
var configurationRoot = builder.Build();
//This is a method that injects various services.
var services = InjectServices();
services.AddSingleton<IConfiguration>(configurationRoot);
var provider = services.BuildServiceProvider();
var my service = provider.GetService<ITest>();
However, I get the following error:
Unable to resolve servifor type 'Microsoft.Extensions.Options.IOptions`1[Test]' while attempting to activate 'Test'.
How can I add IOptions to injection? I thought that services.AddSingleton<IConfiguration>(configurationRoot);
would do the trick, but it doesn't seem to. Also, my configuration is correct, if I use the same appsettings in my main project, there is no problems.
You have forgotten to register services required for using options:
Also, you should setup how to build
CustomSection
from configurations by something like this:Reference Configuration in ASP.NET Core
Reference Options pattern in ASP.NET Core