DbContext decoupling

asp.net-core c# entity-framework-core

Question

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.

1
1
5/22/2018 10:05:07 AM

Accepted Answer

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.

0
5/22/2018 10:26:15 AM

Popular Answer

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.



Related Questions





Related

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