asp.net mvc 5 依赖注入autofac 6.4 使用实例

第一步:启动vs2022后,新建一个asp.net mvc的项目,项目名称为MvcAutofac

第二步:为了测试,在Models文件夹中建立两个测试使用的类,Student.cs、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; }
    }

第三步:新建Repository文件夹,使用仓储数据文件夹,在此文件夹中建立一个接口文件IRepository.cs,内容如下,这里做简单测试,所以只写了两个方法:

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

第四步:在此文件夹中新建StudentRepository.cs类,并继承IRepository.cs接口,在这个文件中我们手工添加了几条数据来进行测试,如下图:

    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);
        }
    }

第五步:在此文件夹中新建BoyRepository.cs类,并继承IRepository.cs接口,在这个文件中我们手工添加了几条数据来进行测试,如下图:

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

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

第六步:浏览NUGET程序包管理器,搜索autofac.mvc5并安装完成,将会自动安装autofac6.4版本

第七步:打开项目根目录下的Global.asax文件,并添加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));

        }
    }
}

第八步:打开Controllers文件夹,并打开HomeController.cs文件,我们直接在这上面修改吧,这比较简单。

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

        //在构造函数中直接注入
        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);
        }
    }

第九步:修改Index对应的视图文件 Index.cshtml文件,如下图代码:

@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>

第十步:最终呈现的结果如下图所示:

好了,就这么简单,你学会了吗?

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值