翼度科技»论坛 编程开发 .net 查看内容

.Net Framework使用Autofac实现依赖注入

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
.Net Framework使用Autofac实现依赖注入

前言

最近也是找了快2周的工作了,收到的面试邀请也就几个,然后有个面试题目是用asp.net mvc + Entityframework 做一个学生信息增删改查系统。因为题目要求了用Entityframework 也就是EF 那也就不上core了,web项目也是用Framework 4.8去做的。
本文的重点是IOC容器,在Framework 中是没有自带的IOC容器的,那么就需要使用第三方库去实现依赖注入,我这里用的是Autofac。
如果不使用IOC容器去管理类,那么操作数据库和使用类方法则是
  1. using(MydbContext db = new MydbContext){
  2.         db....
  3. }
  4. StudentService s = new StudentService();
  5. s.Add();
复制代码
使用方法

Nuget包

首先需要下载2个Nuget包,分别是:
  1. dotnet add package Autofac --version 7.1.0
复制代码
  1. dotnet add package Autofac.Mvc5 --version 6.1.0
复制代码
配置文件

然后在配置文件中,也就是Global.asax.cs文件
然后需要添加如下代码:
  1. // 创建 Autofac 容器生成器
  2. var builder = new ContainerBuilder();
  3. // 注册 EF 上下文
  4. builder.RegisterType<SchoolContext>().InstancePerRequest();
  5. // 注册其他服务
  6. builder.RegisterType<StudentService>().As<IStudentService>().InstancePerRequest();
  7. // 注册控制器
  8. builder.RegisterControllers(typeof(HomeController).Assembly);
  9. // 构建容器
  10. var container = builder.Build();
  11. // 设置 ASP.NET MVC 的依赖解析器为 Autofac
  12. DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
复制代码
上面我注入了一个SchoolContext数据库上下文服务,用于操作数据库
然后注册了StudentService服务,里面是增删改查代码
举个例子:
  1. public interface IStudentService{
  2.         //删除
  3.         Task<int> DelAsync(int id);
  4. }
  5. public class StudentService:IStudentService
  6. {
  7.         private readonly SchoolContext _dbContext;
  8.         public StudentService(SchoolContext dbContext)
  9.         {
  10.             _dbContext = dbContext;
  11.         }
  12.         public async Task<int> DelAsync(int id)
  13.         {
  14.             var student = _dbContext.Students.Include("Score").FirstOrDefault(s => s.Id == id);
  15.             if (student != null)
  16.             {
  17.                 // 删除关联的成绩表
  18.                 if (student.Score != null)
  19.                 {
  20.                     _dbContext.Scores.Remove(student.Score);
  21.                 }
  22.                 // 删除学生
  23.                 _dbContext.Students.Remove(student);
  24.                 return await _dbContext.SaveChangesAsync();
  25.             }
  26.             return 0;
  27.     }
  28. }
复制代码
上面StudentService类实现了IStudentService接口的方法,并且注入了SchoolContext依赖进行数据库操作。
  1. public class HomeController : Controller
  2. {
  3.         private readonly IStudentService _studentService;
  4.         public HomeController(IStudentService studentService)
  5.         {
  6.             _studentService = studentService;
  7.         }
  8.         public async Task<ActionResult> DelStudent(int id)
  9.         {
  10.             int result = await _studentService.DelAsync(id);
  11.             if (result > 0)
  12.             {
  13.                 TempData["SuccessMessage"] = "学生信息删除成功";
  14.                 return RedirectToAction("Index");   
  15.             }
  16.             TempData["SuccessMessage"] = "学生信息删除失败";
  17.             return RedirectToAction("Index");   
  18.         }
  19. }
复制代码
上面的控制器则是注入了IStudentService然后就可以调用它的删除学生信息的方法了。
我们需要注意的是需要把数据库上下文和服务类交给容器去管理。
  1. // 注册 EF 上下文
  2. builder.RegisterType<SchoolContext>().InstancePerRequest();
  3. // 注册其他服务
  4. builder.RegisterType<StudentService>().As<IStudentService>().InstancePerRequest();
  5. // 注册控制器
  6. builder.RegisterControllers(typeof(HomeController).Assembly);
复制代码
同时也要注册控制器,一开始我去写的的时候没有注册控制器,然后会报构造函数不能为空的错误!
生命周期


  • InstancePerDependency:每次解析时都创建一个新的实例。这是默认的生命周期管理方式。
  • SingleInstance:整个应用程序中只创建一个实例,并在后续的解析中重用该实例。
  • InstancePerLifetimeScope:每个生命周期范围内只创建一个实例。生命周期范围可以通过Autofac的BeginLifetimeScope()方法创建。
  • InstancePerMatchingLifetimeScope:与InstancePerLifetimeScope类似,但只有在解析时与指定的生命周期范围匹配时才会创建实例。
  • InstancePerRequest:在Web应用程序中,每个HTTP请求都创建一个新的实例。这通常用于在Web API或MVC应用程序中注册服务。
  • InstancePerOwned:在每个Owned上创建一个新的实例。Owned是一个特殊的类型,用于在需要时创建和释放实例。
参考资料


来源:https://www.cnblogs.com/ZYPLJ/archive/2023/09/12/17694895.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具