Dbcontext object transient in dotnet core

entity-framework-core

Question

I'm creating an webapi application in dotnet core with entity framework. When I gone through documentation. I can use DI to inject the dbcontext object in dotnet core. But when I'm doing this the whole application using one dbcontext object. How do I make the dbcontext as transient? If any example is there it will really help me.

Please find my existing code below.

This is the code I wrote in ConfigureService

  public void ConfigureServices(IServiceCollection services)
        {
           services.AddDbContext<DataAccess.XXXXContext>(options => options.UseMySQL(Configuration["ConnectionStrings:DefaultConnection"]),ServiceLifetime.Transient);
        }

This is the code i wrote in DBcontext class

 public partial class XXXXContext : DbContext
    {
        private readonly Logger logger = LogManager.GetCurrentClassLogger();

        public XXXXContext(DbContextOptions<XXXXContext> options) :base(options)
        {
            logger.Debug("XXXXContext created");
        }
     }

If you see i have written already Transient in the AddDbContext method.So everytime if it create object. My constructor should call. But i'm getting call only once.

1
0
8/26/2017 8:51:49 PM

Accepted Answer

I`ve already done this using a separated statement.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DataAccess.XXXXContext>(options => options.UseMySQL(Configuration["ConnectionStrings:DefaultConnection"]));

    services.AddTransient<DataAccess.XXXXContext>();
}
0
11/22/2017 12:30:46 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow