Dotnet
Authentication and Authorization - Registration Part 2

Configure Dependency Injection for DB Context

PRO

I finished! On to the next chapter

Outline

Demo: Configuring Dependency Injection for DB Context

In the Conduit.Api Project

Add project reference
  • Conduit.Data
Modify Conduit.Api.Startup.cs file
  • Add the Db Context as Dependency Injection
  • Add the connection string from configuration when it's injected
  • Resolve any Namespace that are needed

Here's the SQL Server Edition of the ConfigureServices method in the Startup.cs file:

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ConduitContext>(options =>
            {
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddScoped<IAccountRepository, AccountRepository>();
            services.AddControllers();
            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {
                    var errors = new SerializableError(context.ModelState);
                    var result = new UnprocessableEntityObjectResult(new { errors });
                    return result;
                };
            });
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Conduit.Api", Version = "v1" });
            });
        }

Here's the Sqlite Edition of the ConfigureServices method in the Startup.cs file:

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ConduitContext>(options =>
            {
                options.UseSqlite(
                    Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddScoped<IAccountRepository, AccountRepository>();
            services.AddControllers();
            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {
                    var errors = new SerializableError(context.ModelState);
                    var result = new UnprocessableEntityObjectResult(new { errors });
                    return result;
                };
            });
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Conduit.Api", Version = "v1" });
            });
        }

Conduit Github Repo

Tag Name: db-context-person-account