How to I access the DbContext of EF core from another project when used in ASP.NET core? c# dependency-injection entity-framework entity-framework-core


I followed the pattern to use EF Core with ASP.NET core and all is well. But recently I created a 'Calculation' project and want to make database calls from it.

The problem is I don't know how to create a new DbContextOptions. In my code that is done with

   services.AddDbContext<RetContext>(options => options

But in a new .NET core class I need to provide it manually. How do I do this ? My code is like this:

 public static class LoadData
    public static IConfiguration Configuration { get; }

    public static RefProgramProfileData Load_RefProgramProfileData(string code)
        // var optionsBuilder = new DbContextOptionsBuilder<RetContext>();
        // optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));

        //How do I make an optionsbuilder and get the configuration from the WEB project?
       UnitOfWork uow = new UnitOfWork(new RetContext(optionsBuilder));

        var loadedRefProgramProfileData  = uow.RefProgramProfileDataRepository
            .Find(x => x.ProgramCode == code).FirstOrDefault();

        return loadedRefProgramProfileData;
6/11/2018 10:13:21 PM

Accepted Answer

You may instantiate your DbContext like this:

var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
var configuration = builder.Build();
var optionsBuilder = new DbContextOptionsBuilder<RetContext>();
_context = new RetContext(optionsBuilder.Options); 

However, the ideal is to use dependency injection. Let's say you have a class CalculationService in your other project. For that, you need to register that class as a service that can be injected:


Then your class can receive DbContext (or any other services) through DI:

public class CalculationService
    private RetContext _context;

    public CalculationService(RetContext context)
        _context = context;

Naturally, you won't be able to instantiate your class manually like this:

var service = new CalculationService();

Instead, you'd need to make whatever class needs to use your CalculationService to also receive it through DI and make that class injectable as well.

8/29/2019 3:02:55 AM

Related Questions


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