Model
创建IStudentRepository
public interface IStudentRepository//加public,默认私有
{
public Student Add(Student student);
public Student GetStudent(int id);
}
StudentRepository下
public class StudentRepository:IStudentRepository//继承
{}
HomeControllers
public class HomeController : Controller
{
IStudentRepository _studentRepository;
public HomeController(IStudentRepository studentRepository)
{
_studentRepository = studentRepository;
}
public string Index()
{
Student s = _studentRepository.GetStudent(1);
return s.Name;
}
public string Add()
{
Student s = new Student();
_studentRepository.Add(s);
return "sucess";
}
}
Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IStudentRepository, StudentRepository>();//依赖关系引入
}