Doğaç Özen
Doğaç Özen

Reputation: 133

DbContext decoupling

I already to put my EF related code in a class library and use it in an asp.net webapi project. However I still have the following code in my webapi project.

services.AddDbContext<MyOwnDbContext>(
    ops => ops.UseSqlite(connection, optionsBuilder => optionsBuilder.MigrationsAssembly("MyProject.API")));

Is there a way to decouple 'MyOwnDbContext: DbContext' class completely from webapi project (using a factory or an interface). Or this is an unnecessary concern? I just don't want to use EF related library in two projects.

Upvotes: 2

Views: 697

Answers (2)

Camilo Terevinto
Camilo Terevinto

Reputation: 32072

I would leave it alone, since you still have to have installed Entity Framework in the entry project so that the library can use it (or hack the way through by copying files manually, but let's not get into that).

However, this is what I did in a recent project where I wanted to keep all my services in a single place, different to the Startup class:

  1. Install Microsoft.Extensions.DependencyInjection to the project where you want your DbContext.
  2. Add something like this:

    public static class Injector
    {
        // you probably want to pass the connection string or an Options class here too
        public static IServiceCollection Inject(this IServiceCollection services)
        {
            services.AddDbContext<...>(...);
    
            return services;
        }
    }
    
  3. Inject it, rather than the context itself:

    public void Configure(IServiceCollection services)
    {
        services.Inject();
    
        // and whatever else you need 
        services.AddMvc();
    }
    

Like this, you do not win a lot, but you could keep going as I mentioned at the beginning.

Upvotes: 3

chrisb-de
chrisb-de

Reputation: 71

This is an uneccessary concern. You put this into the root of your application (Startup.cs). Everything is hardwired here (Dependency Injection Container, Contexts, Logging,...).

In fact there is no better place to put it. Because the configuration of the context itself is of no concern for any layer below the application level. Your DAL/Repositories just use the already configured context and that's it.

Upvotes: 0

Related Questions