Navigation

Saturday 28 September 2019

Implementing the Singleton Pattern in ASP.NET Core with Simple Example



The structure of project is shown as below screenshot.





Step 1: Create a class with the name 'Applicant.cs' and copy and paste the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SingletonPatternCore.Model
{
    public class Applicant
    {
        public int ApplicantId { get; set; }
        public string FName { get; set; }
        public string LName { get; set; }
        public int Dept { get; set; }
    }

}

Step 2: Create an interface with the name 'IApplicant.cs' and copy and paste the following code.


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SingletonPatternCore.Model
{
    public interface IApplicant
    {
        Applicant SaveEmployee(Applicant emp);
        IEnumerable GetEmployees(int id);
        IEnumerable GetAllEmployees();

    }
}



Step 3: Create a class with the name 'MockApplicantRepository.cs', copy and paste the following code.


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SingletonPatternCore.Model
{
    public class MockApplicantRepository : IApplicant
    {
        private List<Applicant> _lst;
        public MockApplicantRepository()
        {
          _lst = new List<Applicant>()
          {
           new Applicant(){ApplicantId = 1, FName = "Ashok", LName = "Kumar", Dept = 10 },
           new Applicant() { ApplicantId = 2, FName = "Mukesh", LName = "Kumar", Dept = 10 },
           new Applicant() { ApplicantId = 3, FName = "Sanjay", LName = "Kumar", Dept = 10 }
          };
        }

        public IEnumerable GetAllEmployees()
        {
            return _lst;
        }

        public IEnumerable GetEmployees(int id)
        {
           return _lst.Where(w => w.ApplicantId == id);
        }

        public Applicant SaveEmployee(Applicant emp)
        {
            emp.ApplicantId = _lst.Max(e => e.ApplicantId) + 1;
            _lst.Add(emp);
            return emp;
        }
    }
}


Step 4: Create a  controller with the name ApplicantController, copy and paste the following code.



using Microsoft.AspNetCore.Mvc;
using SingletonPatternCore.Model;
using System.Collections;

namespace SingletonPatternCore.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ApplicantController : ControllerBase
    {
        private IApplicant _emp;
        public ApplicantController(IApplicant emp)
        {
            _emp = emp;
        }
        [HttpGet]
        public IEnumerable Get()
        {
            return _emp.GetAllEmployees();
        }
        [HttpPost("SaveEmployee")]
        public Applicant Post([FromBody]Applicant emp)
        {
            return _emp.SaveEmployee(emp);
        }
        [HttpGet("GetEmployeeById/{Id}")]
        public IEnumerable GetEmployeeById(int Id)
        {
           return _emp.GetEmployees(Id);
        }
       
    }
}


Step 5: Following code, you have to add on Startup.cs file.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SingletonPatternCore.Model;

namespace SingletonPatternCore
{
    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.AddMvc();
            //You can add AddSingleton, AddTransient and AddScoped
            services.AddSingleton<IApplicant, MockApplicantRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}


Following are the way to test API as shown in the screenshot.






No comments:

Post a Comment