asp.net mvc 5 dependency injection autofac 6.4 usage examples

Step 1: After starting vs2022, create a new asp.net mvc project with the project name MvcAutofac

Step 2: For testing, create two classes for testing in the Models folder, Student.cs and Boy.cs

 public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class Boy
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }

Step 3: Create a new Repository folder, use the warehousing data folder, and create an interface file IRepository.cs in this folder. The content is as follows. A simple test is done here, so only two methods are written:

 public interface IRepository<T> where T:class
    {
        T GetById(int id);
        List<T> GetAll();
    }

Step 4: Create a new StudentRepository.cs class in this folder and inherit the IRepository.cs interface. In this file, we manually added several pieces of data for testing, as shown below:

 public class StudentRepository : IRepository<Student>
    {
        List<Student> students=new List<Student>()
        {
            new Student(){Id=1,Age = 25,Name = "caifox"},
            new Student(){Id=2,Age = 35,Name = "wanghai"},
            new Student(){Id=3,Age = 45,Name = "liuyang"},
            new Student(){Id=4,Age = 55,Name = "lining"},
            new Student(){Id=5,Age = 65,Name = "zhangxuan"},
        };
        public List<Student> GetAll()
        {
            return students;
        }

        public Student GetById(int id)
        {
            return students.FirstOrDefault(a => a.Id == id);
        }
    }

Step 5: Create a new BoyRepository.cs class in this folder and inherit the IRepository.cs interface. In this file, we manually added several pieces of data for testing, as shown below:

 public class BoyRepository : IRepository<Boy>
    {
        List<Boy> boys = new List<Boy>()
        {
            new Boy(){Id=1,Description = "5 years old",Name = "Boycaifox"},
            new Boy(){Id=2,Description = "35 years old",Name = "Boywanghai"},
            new Boy(){Id=3,Description = "45 years old",Name = "Boyliuyang"},
            new Boy(){Id=4,Description = "55 years old",Name = "Boylining"},
            new Boy(){Id=5,Description = "65 years old",Name = "Boyzhangxuan"},
        };
        public List<Boy> GetAll()
        {
            return boys.ToList();
        }

        public Boy GetById(int id)
        {
            return boys.Find(x => x.Id == id);
        }
    }

Step 6: Browse the NUGET package manager, search for autofac.mvc5 and complete the installation. The autofac6.4 version will be automatically installed.

Step 7: Open the Global.asax file in the project root directory and add a reference to autofac.

using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using MvcAutofac.Models;
using MvcAutofac.Repository;


namespace MvcAutofac
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var builder = new ContainerBuilder();

            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            builder.RegisterType<StudentRepository>().As<IRepository<Student>>();
            builder.RegisterType<BoyRepository>().As<IRepository<Boy>>();

            var container=builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        }
    }
}

Step 8: Open the Controllers folder and open the HomeController.cs file. Let’s modify it directly. This is relatively simple.

 public class HomeController : Controller
    {
        public IRepository<Student> _studentRepository;
        public IRepository<Boy> _boyRepository;
        public HomeController(){}

        //Inject directly in the constructor
        public HomeController(IRepository<Student> studentRepository, IRepository<Boy> boyRepository)
        {
            _studentRepository = studentRepository;
            _boyRepository = boyRepository;
        }
        public ActionResult Index()
        {
            IEnumerable<Student> students = _studentRepository.GetAll();
            List<Boy> boys=_boyRepository.GetAll();
            ViewData["boys"] = boys;
            return View(students);
        }
    }

Step 9: Modify the view file Index.cshtml file corresponding to Index, as shown in the following code:

@using MvcAutofac.Models
@model IEnumerable<MvcAutofac.Models.Student>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Age)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Age)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

</table>

@{ List<Boy> boys= ViewData["boys"] as List<Boy>; }
<table class="table">
    <tr>
        <th>
            ID
        </th>
        <th>
            Name
        </th>
        <th></th>
    </tr>

    @foreach (var item in boys) {
        <tr>
            <td>
                @item.Id
            </td>
            <td>
                @item.Name
            </td>
            <td>
                @item.Description
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
            </td>
        </tr>
    }

</table>

Step 10: The final result is shown in the figure below:

Okay, it’s that simple, have you learned it?