Search code examples
c#dependency-injectionentity-framework-core

AddScoped in dependency injection


I have been reading and its best that I use AddScoped in my EF Core project so I can use many contexts for my updates , so I can stop the 'already tracked' error message when I am doing my SaveChanges.

Here is my code for the dependency injection. Just wondering how I can make this 'AddScoped' instead of Singleton ?

I am pretty new to this Dependency Injection, EF Core etc.

 public override void Configure(IFunctionsHostBuilder builder)
    {
        // CCT database
        builder.Services.AddDbContext<sqldbCCTUKSATPPreProdContext>(
            options =>
            {
                const string ConnString = "SQLConnectionStringCCT";
                options.UseSqlServer(Configuration.GetConnectionString(ConnString)).UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll);
            });
        // CL database (Segimport DB)
        builder.Services.AddDbContext<sqldbCLSegImportUKSATPPreProdContext>(
            options =>
            {
                const string CLConnString = "SQLConnectionStringCL";
                options.UseSqlServer(Configuration.GetConnectionString(CLConnString)).UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll);
                options.EnableSensitiveDataLogging();

            });

Solution

  • AddDbContext registers context as scoped by default - see the default value for contextLifetime which is ServiceLifetime.Scoped. Your problem with "already tracked" comes from somewhere else.