punkouter
punkouter

Reputation: 5366

How to I access the DbContext of EF core from another project when used in ASP.NET 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
            .UseLazyLoadingProxies()
            .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

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;
    }
}

Upvotes: 5

Views: 7352

Answers (1)

Alisson Reinaldo Silva
Alisson Reinaldo Silva

Reputation: 10705

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>();
optionsBuilder.UseSqlServer(configuration.GetConnection("DefaultConnection"));
_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:

services.AddScoped<CalculationService>();

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.

Upvotes: 4

Related Questions