Home

Cannot correctly configure an EF Core Interceptor

edited December 2023

Hi,

Due to my inexperience, I'm having trouble properly configuring my script to execute after I added EF interceptors to my project. The interceptor itself is a SaveChangesInterceptor and works correctly. It has been added to my project service collection as a scoped service and is being injected in my DbContext constructor.

On my LINQPad script, I thought I could do the same. But this results in an error:

CS7036 There is no argument given that corresponds to the required parameter 'publishDomainEventsInterceptor' of 'SmesDbContext.SmesDbContext(DbContextOptions, PublishDomainEventsInterceptor)'

I understand I have to pass an instance of the interceptor to my DbContext constructor. But I can't see how I can do that on the LINQPad script. The only way I have to get the script to run is to remove the interceptor from the DbContext constructor n my project code.

async Task Main()
{
    Console.SetOut(TextWriter.Null);
    Debugger.Launch();

    Assembly applicationAssembly = AppDomain.CurrentDomain.GetAssemblies()
        .Single(assembly => assembly.GetName().Name == "Smes.Application");

    using IHost host = Host
    .CreateDefaultBuilder()
    .ConfigureServices((_, services) =>
        services
            .AddDbContext<SmesDbContext>((serviceProvider, options) =>
            {
                var interceptor = serviceProvider.GetRequiredService<PublishDomainEventsInterceptor>();

                options.UseLazyLoadingProxies()
                       .UseSqlServer("Server=(local);Database=SMESDATA;Trusted_Connection=True;Encrypt=false;")
                       .AddInterceptors(interceptor)
                       .LogTo(_ => { });
            })
            .AddScoped<IUnitOfWorkData, UnitOfWorkData>()
            .AddHttpContextAccessor()
            .AddScoped<PublishDomainEventsInterceptor>()
            .AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(applicationAssembly))
            .AddScoped<IUserContextService, UserContextService>()
            .AddScoped<IDateTimeProvider, DateTimeProvider>())
    .Build();

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        var data = services.GetRequiredService<IUnitOfWorkData>();
        var mediatr = services.GetRequiredService<IMediator>();

        await Execute(data, mediatr);
    }
}

Comments

Sign In or Register to comment.