摘自小牛
例子:
首先orm ef(此文用的dbfirst方式):
数据库创建表Books,然后项目中用nuget安装ef包,创建EFDbContext上下文类,
public class EFDbContext : DbContext { public DbSetBooks { get; set; } }
然后web.config配置链接数据库字符串,name和上下文类的类名需要一样才能映射
name="EFDbContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=BookShop;User ID=sa;Password=sa" providerName="System.Data.SqlClient" />
,
创建model,model类有 Book
接口类,有 IBookRepository
实现接口类有 BookRepository ,且创建上下文类实体类
public class BookRepository : IBookRepository { private EFDbContext context = new EFDbContext(); public IQueryableBooks { get { return context.Books; } } }
创建ninjectfactory类
主要改动有,在AddBindings方法中
private void AddBindings() {
ninjectKernel.Bind
}
对接口类和实现接口类进行绑定
在Application_Start方法中
protected void Application_Start() { ...... //设置Controller工厂 ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); }
最后,在controller中,构造函数等
右击BookShop.WebUI工程的Controllers文件夹,添加一个名为Book的Controller,按下面代码对其进行编辑:
public class BookController : Controller {
private IBookRepository repository;
public BookController(IBookRepository bookRepository) {
repository = bookRepository;
}
}
在这,BookController的构造函数接受了一个IBookRepository参数,当BookController被实例化的时候,Ninject就为其注入了BookRepository的依赖。接下来我们为这个Controller添加一个名为List的Action,用来呈现Book列表。代码如下:
public class BookController : Controller {
...
public ViewResult List() {
return View(repository.Books);
}
}