Marcelo Oliveto
Marcelo Oliveto

Reputation: 867

Asp.Net-5 Class Library (Package) Test Inject IOptions

I have created a new proyect: Class Library (Package) to test my repositories, because i need test a DataRepository tier that i am consuming from asp.net vnext.

I want use DI like asp.net vnext but i can't create an instance from IServiceCollection and inject IOptions.

i have tried with

var serviceProvider = new ServiceCollection()
    .AddTransient<ISampleRepository, SampleRepository>()
    .BuildServiceProvider();

The Ctor of the SampleRepository is

public SampleRepository(IOptions<Settings> settings)

But i am having the following error message:

Result Message: Unable to resolve service for type 'Microsoft.Framework.OptionsModel.IOptions`1[Repository.Sample.Settings]' while attempting to activate 'Repository.Sample.SampleRepository'.

Upvotes: 3

Views: 409

Answers (2)

Stafford Williams
Stafford Williams

Reputation: 9806

You still need to populate and register that Repository.Sample.Settings object:

serviceProvider.Configure<Settings>(Configuration.GetSection("Settings"));

or;

serviceProvider.Configure<Settings>(options =>
{
    options.MyField1 = Configuration["Settings:MyField1"];
    options.MyField2 = Configuration["Settings:MyField2"];
});

Upvotes: 1

Kiran
Kiran

Reputation: 57969

You would need to add the OptionsManager service to resolve types like IOptions<>

.Add(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(OptionsManager<>)));

Upvotes: 1

Related Questions