Follow us

Header Ads

DependencyInjection in Asp.Net Core

DependencyInjection in Asp.Net Core

Package

  • "Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.5" 
  • "Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.5" 
  • "Microsoft.EntityFrameworkCore.Tools" Version="3.1.15" 
  •  "Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.5" 

Controllers[Folder]

HomeController.cs

using DependencyInjection.infrastructure;
using DependencyInjection.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace DependencyInjection.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IStudentRepo _repo;

        public HomeController(ILogger<HomeController> logger, IStudentRepo Repo)
        {
            _logger = logger;
            _repo = Repo;
        }
       
        public IActionResult Index()
        {
            var items = _repo.GetAll();
            return View(items);
        }
        public IActionResult Details(int id)
        {
            var item = _repo.GetByID();
            return View(item);
        }
        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Data[Folder]

ApplicationDbContex.cs

using DependencyInjection.Models;
using Microsoft.EntityFrameworkCore;

namespace DependencyInjection.Data
{
    public class ApplicationDbContex : DbContext
    {
        public ApplicationDbContex(DbContextOptions<ApplicationDbContex> options): base(options)
        {
            
        }
        public DbSet<Student> Students { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Student>().HasData(
            new Student {Id=55, Name="Tarun", Email="abc@outlook.com" },
              new Student { Id = 56, Name = "Tarun1", Email = "abc1@outlook.com" }
                );
        }
    }
}

infrastructure[Folder]

IStudentRepo.cs

using DependencyInjection.Models;
using System.Collections.Generic;

namespace DependencyInjection.infrastructure
{
    public interface IStudentRepo
    {
        List<Student> GetByID();
        Student GetByID(int Id);
        object GetAll();
    }
}

Models[Folder]

Student.cs

using System.ComponentModel.DataAnnotations;

namespace DependencyInjection.Models
{
    public class Student
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        [Required]
        public string Email { get; set; }
    }
}


Repository[Folder]

StudentRepo.cs

using DependencyInjection.Data;
using DependencyInjection.infrastructure;
using DependencyInjection.Models;
using System.Collections.Generic;
using System.Linq;

namespace DependencyInjection.Repository
{
    public class StudentRepo : IStudentRepo
    {
        private readonly ApplicationDbContex _context;

        public StudentRepo(ApplicationDbContex context)
        {
            _context = context;
        }

        public object GetAll()
        {
            throw new System.NotImplementedException();
        }

        public List<Student> GetByID()
        {
            return _context.Students.ToList();
        }

        public Student GetByID(int Id)
        {
            return _context.Students.FirstOrDefault(x => x.Id == Id);
        }
    }
}

Views[Folder]

Index.cshtml

@model IEnumerable<DependencyInjection.Models.Student>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Email)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Email)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=CHETUIWK1048\\SQLDEV2019;Database=DIDB;Trusted_Connection=True;MultipleActiveResultSets=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Startup.cs

using DependencyInjection.Data;
using DependencyInjection.infrastructure;
using DependencyInjection.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DependencyInjection
{
    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.AddControllersWithViews();
            services.AddDbContext<ApplicationDbContex>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddTransient<IStudentRepo, StudentRepo>();
        }

        // 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.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}



Post a Comment

0 Comments