Mateusz Kaleta
Mateusz Kaleta

Reputation: 309

What's the Microsoft.Extensions.DependencyInjection equivalent to Autofac's lambda registration?

With Autofac we can register a dependency using a lambda registration, as follows:

builder.Register(c => GetCommandContext()).As<IAppDbContext>();

I want achieve the same with the built-in ASP.NET Core DI container.

This is what I tried:

services.AddScoped<IAppQuerier, AppQuerier>();  // this is standard registration

services.AddScoped<IAppDbContext, GetCommandContext()>(); // This doesn't compile

private IAppDbContext GetCommandContext()
{
    //for example
    var appDbContext = Substitute.For<ICommandsContext>();
    var roundOccurrences = AppTestsData.GetRoundOccurrences();
    appDbContext.RoundOccurrences.Returns(roundOccurrences);

    return appDbContext;
}

Upvotes: 0

Views: 460

Answers (1)

Nkosi
Nkosi

Reputation: 247551

What you want is the factory delegate

services.AddScoped<IAppDbContext>(sp => GetCommandContext());

The sp is an instance of IServiceProvider

Upvotes: 1

Related Questions