.Net Framework使用Autofac實(shí)現(xiàn)依賴注入
前言
最近也是找了快2周的工作了,收到的面試邀請(qǐng)也就幾個(gè),然后有個(gè)面試題目是用asp.net mvc + Entityframework 做一個(gè)學(xué)生信息增刪改查系統(tǒng)。因?yàn)轭}目要求了用Entityframework 也就是EF 那也就不上core了,web項(xiàng)目也是用Framework 4.8去做的。
本文的重點(diǎn)是IOC容器,在Framework 中是沒有自帶的IOC容器的,那么就需要使用第三方庫(kù)去實(shí)現(xiàn)依賴注入,我這里用的是Autofac。
如果不使用IOC容器去管理類,那么操作數(shù)據(jù)庫(kù)和使用類方法則是
using(MydbContext db = new MydbContext){
db....
}
StudentService s = new StudentService();
s.Add();
使用方法
Nuget包
首先需要下載2個(gè)Nuget包,分別是:
dotnet add package Autofac --version 7.1.0
dotnet add package Autofac.Mvc5 --version 6.1.0
配置文件
然后在配置文件中,也就是Global.asax.cs
文件
然后需要添加如下代碼:
// 創(chuàng)建 Autofac 容器生成器
var builder = new ContainerBuilder();
// 注冊(cè) EF 上下文
builder.RegisterType<SchoolContext>().InstancePerRequest();
// 注冊(cè)其他服務(wù)
builder.RegisterType<StudentService>().As<IStudentService>().InstancePerRequest();
// 注冊(cè)控制器
builder.RegisterControllers(typeof(HomeController).Assembly);
// 構(gòu)建容器
var container = builder.Build();
// 設(shè)置 ASP.NET MVC 的依賴解析器為 Autofac
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
上面我注入了一個(gè)SchoolContext數(shù)據(jù)庫(kù)上下文服務(wù),用于操作數(shù)據(jù)庫(kù)
然后注冊(cè)了StudentService服務(wù),里面是增刪改查代碼
舉個(gè)例子:
public interface IStudentService{
//刪除
Task<int> DelAsync(int id);
}
public class StudentService:IStudentService
{
private readonly SchoolContext _dbContext;
public StudentService(SchoolContext dbContext)
{
_dbContext = dbContext;
}
public async Task<int> DelAsync(int id)
{
var student = _dbContext.Students.Include("Score").FirstOrDefault(s => s.Id == id);
if (student != null)
{
// 刪除關(guān)聯(lián)的成績(jī)表
if (student.Score != null)
{
_dbContext.Scores.Remove(student.Score);
}
// 刪除學(xué)生
_dbContext.Students.Remove(student);
return await _dbContext.SaveChangesAsync();
}
return 0;
}
}
上面StudentService類實(shí)現(xiàn)了IStudentService接口的方法,并且注入了SchoolContext依賴進(jìn)行數(shù)據(jù)庫(kù)操作。
public class HomeController : Controller
{
private readonly IStudentService _studentService;
public HomeController(IStudentService studentService)
{
_studentService = studentService;
}
public async Task<ActionResult> DelStudent(int id)
{
int result = await _studentService.DelAsync(id);
if (result > 0)
{
TempData["SuccessMessage"] = "學(xué)生信息刪除成功";
return RedirectToAction("Index");
}
TempData["SuccessMessage"] = "學(xué)生信息刪除失敗";
return RedirectToAction("Index");
}
}
上面的控制器則是注入了IStudentService然后就可以調(diào)用它的刪除學(xué)生信息的方法了。
我們需要注意的是需要把數(shù)據(jù)庫(kù)上下文和服務(wù)類交給容器去管理。
// 注冊(cè) EF 上下文
builder.RegisterType<SchoolContext>().InstancePerRequest();
// 注冊(cè)其他服務(wù)
builder.RegisterType<StudentService>().As<IStudentService>().InstancePerRequest();
// 注冊(cè)控制器
builder.RegisterControllers(typeof(HomeController).Assembly);
同時(shí)也要注冊(cè)控制器,一開始我去寫的的時(shí)候沒有注冊(cè)控制器,然后會(huì)報(bào)構(gòu)造函數(shù)不能為空的錯(cuò)誤!
生命周期
- InstancePerDependency:每次解析時(shí)都創(chuàng)建一個(gè)新的實(shí)例。這是默認(rèn)的生命周期管理方式。
- SingleInstance:整個(gè)應(yīng)用程序中只創(chuàng)建一個(gè)實(shí)例,并在后續(xù)的解析中重用該實(shí)例。
- InstancePerLifetimeScope:每個(gè)生命周期范圍內(nèi)只創(chuàng)建一個(gè)實(shí)例。生命周期范圍可以通過Autofac的
BeginLifetimeScope()
方法創(chuàng)建。 - InstancePerMatchingLifetimeScope:與
InstancePerLifetimeScope
類似,但只有在解析時(shí)與指定的生命周期范圍匹配時(shí)才會(huì)創(chuàng)建實(shí)例。 - InstancePerRequest:在Web應(yīng)用程序中,每個(gè)HTTP請(qǐng)求都創(chuàng)建一個(gè)新的實(shí)例。這通常用于在Web API或MVC應(yīng)用程序中注冊(cè)服務(wù)。
- InstancePerOwned:在每個(gè)
Owned<T>
上創(chuàng)建一個(gè)新的實(shí)例。Owned<T>
是一個(gè)特殊的類型,用于在需要時(shí)創(chuàng)建和釋放實(shí)例。
參考資料
-
控制范圍和生存期 — Autofac 7.0.0 文檔 https://autofac.readthedocs.io/en/latest/lifetime/index.html#example-web-application文章來源:http://www.zghlxwxcb.cn/news/detail-707936.html
-
NuGet 畫廊 |Autofac.Mvc5 6.1.0 https://www.nuget.org/packages/Autofac.Mvc5文章來源地址http://www.zghlxwxcb.cn/news/detail-707936.html
到了這里,關(guān)于.Net Framework使用Autofac實(shí)現(xiàn)依賴注入的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!