简体   繁体   中英

Get DbContext Instance used by asp.net boilerplate repository

I started a new project using Aspnet Boiler plate, but no longer feel like using repositories and tons of hidden engineering done behind the scene.

Hence looking forward to get instance the db context instantiated by Abp repositories framework and

  1. work with Ef core LINQ queries directly.
  2. Commit my changes directly using SaveChanges, rather than relying on abstracted transactions.

How do I fetch that instance please?

  1. work with Ef core LINQ queries directly.

You can get an instance of DbContext using GetDbContext() of IDbContextProvider .

private readonly YourDbContext _ctx;

public YourService(IDbContextProvider<YourDbContext> dbContextProvider)
{
    _ctx = dbContextProvider.GetDbContext();
}
  1. Commit my changes directly using SaveChanges, rather than relying on abstracted transactions.

You can disable transactions by applying [UnitOfWork(IsDisabled = true)] attribute

Here is a relevant article on transaction management with ASP.NET Boilerplate.

@NitinSawant I had a similar issue, though in my case the parameter in question was specifically called out as unitOfWork . I had a database sweep-and-update seed helper class that was run from the Postinitialize method of a module:

public override void PostInitialize()
{
    // The hypothetical 'SweeperClass' in this example uses constructor
    // injection to obtain a IDbContextProvider instance and from there
    // get hold of a DbContext.
    //
    // As written, this code threw a null argument exception.

    var sweeperClass = IocManager.Resolve<SweeperClass>();
    // ...do stuff...
}

In this case, it was fortunately just a question of also resolving a unit of work to wrap the other object's construction.

using Abp.Domain.Uow;

public override void PostInitialize()
{
    using (IocManager.Resolve<IUnitOfWorkManager>().Begin())
    {
        var sweeperClass = IocManager.Resolve<SweeperClass>();
        // ...do stuff...
    }
}

So @koryakinp's answer gave me most of the solution and I just needed the above adjustment to get things going for my particular use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM