Blog

Filter posts by Category Or Tag of the Blog section!

Register EF Core DBContext in data layer assembly

Tuesday, 12 December 2017

In Asp.net core samples, you always see the AddDbContext method In services to register Entity framework DbContext. I mean something like below:

 

  public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddApiVersioning(o => o.ApiVersionReader = new HeaderApiVersionReader("api-version"));
            services.AddDbContext<BaseDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));        
        }
}

 

Suppose that we have an architecture that forces us to have loosely coupled services. For example, our EF DbContext lives in the Data Access layer and  the presentation layer should not know anything about that as it is talking to a service layer:

  1. Presentation
  2. Service
  3. Data Access

In order to register each of the above configurations in its own layer, we should create an extension method over IServiceCollection :

 

public static class DataRegistery
    {
        public static IServiceCollection RegisterData(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

            services.AddEntityFrameworkSqlServer().AddDbContext<DataContext>(options =>
            {
                options.UseSqlServer(configuration.GetConnectionString("MyConnection"));
            });

            return services;
        }
    }

 

And we can register this in Service layer configuration :

 

 public static class ServiceRegistery
    {
        public static IServiceCollection RegisterService(this IServiceCollection services, IConfiguration configuration)
        {
            services.RegisterData(configuration);

            return services;
        }
    }

 

And finally in asp.net core Startup class:

 

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
            services.RegisterService(Configuration);
        }
}

 

Cheers!

comments powered by Disqus