Home > Net >  How to inject method into DI Container in ASP.NET Core?
How to inject method into DI Container in ASP.NET Core?

Time:08-13

I want to inject fake method in asp.net core DI container.

I want something like :

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

services.AddScoped<IAppDbContext, GetCommandContext()>();

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

            return appDbContext;
        }

In AutoFac the method looks like this:

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

CodePudding user response:

What you want is the factory delegate

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

The sp is an instance of IServiceProvider

  • Related