Home > Net >  DI DbContext in data layer?
DI DbContext in data layer?

Time:09-18

So I'm trying to seperate concerns of my project and properly isolate layers. Therefore the layers I have are:

Web, Domain and Data

I've noticed from several answers on S/O that the best designs are especially when the data access is not known and is self contained in the data layer. Since with this approach I need to DI the DbContext in my Web project, however this exposes that the Data layer is using EntityFrameworkCore to the Web project like so:

Startup:

 public void ConfigureServices(IServiceCollection services)
 {
     services.AddDbContext<ApplicationDbContext>(option =>
         option.UseSqlServer(_configuration.GetConnectionString("Data")));
 }

Is there any way to just DI this in the Data project thus hiding what the Data layer is using from the Web project?

CodePudding user response:

I believe you choose wrong approach and you cant DI in data layer. but for your final sentence (DI out side of main layer), we use db context in unit test project like this:

lock (_lock)
        {
            if (!_databaseInitialized)
            {
                using (var context = CreateContext())
                {
                    context.Database.EnsureDeleted();
                    context.Database.EnsureCreated();

                    context.AddRange(
                        new Blog { Name = "Blog1", Url = "http://blog1.com" },
                        new Blog { Name = "Blog2", Url = "http://blog2.com" });
                    context.SaveChanges();
                }

                _databaseInitialized = true;
            }
        }

again, this is wrong approach and its completely wrong. DI supply lots of feature that you should use them. plus i think you can use other lib for injecting services (not db context)

CodePudding user response:

I recommend you to add such Extension Method to the Data Layer

public static class ServiceExtensions
{
    public static void AddDataLayer(this IServiceCollection services,  IConfiguration configuration)
    {
        services.AddDbContext<ApplicationDbContext>(option =>
             option.UseSqlServer(configuration.GetConnectionString("Data")));
    }
}

and then call it in the Web Layer as follows

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataLayer(_configuration);
}

So you can hide EntityFrameworkCore existence from Web Layer.
The Web Layer already knows about the existence of the Data Layer. So you won't break anything.

  • Related