Home > Mobile >  What's the Microsoft.Extensions.DependencyInjection equivalent to Autofac's lambda registr
What's the Microsoft.Extensions.DependencyInjection equivalent to Autofac's lambda registr

Time:08-13

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;
}

CodePudding user response:

What you want is the factory delegate

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

The sp is an instance of IServiceProvider

  • Related