model创建StudentDB类
public class StudentDB : IStudentRepository
{
public Student Add(Student student)
{
throw new NotImplementedException();
}
public Student GetStudent(int id)
{
Student s = new Student { Id=999,Name="李荣浩",ClassName="音乐学院"};
return s;
}
}
startup
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IStudentRepository, StudentDB>();//切换
}
生命周期
一.Singleton
1.创建Add.cshtml文件
@using StudentMVC.Models
@inject IStudentRepository _studentRepository
<div>
<form method="post">
<input type="submit" value="添加" />
</form>
</div>
<div>
学生总数:@_studentRepository.GetAllStudents().Count.ToString()
</div>
2.HomeControllers下
public IActionResult Add()
{
return View();
}
[HttpPost]
public IActionResult Add(string name)
{
_studentRepository.Add(new Student { Name="崔恩娜",Email="213@qq.com"});
return View();
}
3.startup下
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IStudentRepository,StudentRepository>();
}
二.scoped
一次http请求到结束 1次
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//services.AddSingleton<IStudentRepository,StudentRepository>();
services.AddScoped<IStudentRepository, StudentRepository>();
}
三.Transient
瞬时,新new
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//services.AddSingleton<IStudentRepository,StudentRepository>();
//services.AddScoped<IStudentRepository, StudentRepository>();
services.AddTransient<IStudentRepository, StudentRepository>();
}