Demo: Implementing Dependency Injection

In Conduilt.Api Project
  • Modify Startup.cs, ConfigureService method
  • Include the following code: services.AddScoped<IAccountRepository, AccountRepository>(); // notice Interface vs. class
  • Fix the using statements.

Result of the C# code for the Startup.cs file:

using Conduit.Repositories;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;

namespace Conduit.Api
    public class Startup
        public Startup(IConfiguration configuration)
            Configuration = configuration;

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
            services.AddScoped<IAccountRepository, AccountRepository>();
            services.AddSwaggerGen(c =>
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Conduit.Api", Version = "v1" });

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            if (env.IsDevelopment())
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Conduit.Api v1"));




            app.UseEndpoints(endpoints =>

That's it! ASP.NET will now take responsibility for building the object tree of dependencies and provide it to your Controller.


Let's run it and watch it work.

Test validation:
  • Provide all required values results 200
  • Change password to "password" results 400
  • Remove username results 400
  • Remove @ from email results 400
  • Remove email results 400

Resources: • https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/models-data/validation-with-the-data-annotation-validators-cs • https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations