我真的很困惑,我从“Apress pro Asp.net Mvc 4”一书中了解到,Mvc 4 的最佳模式是依赖注入,(将数据库的模型数据等......放在另一个项目中(域)然后为这些接口创建接口和实现,然后使用 Ninja 将其连接到控制器。
并且所有连接到 db 仅来自数据层解决方案,viewModel 中的 web 解决方案中唯一的模型
控制器
public class ProductController : Controller
{
private IProductRepository repository;
public ProductController(IProductRepository productRepository)
{
this.repository = productRepository;
}
....
}
和忍者
ninjectKernel.Bind<IProductRepository>().To<EFProductRepository>();
另一方面,在我的上一份工作(网站管理员)中,公司为 mvc 项目使用了另一种模式(我现在正在使用这种模式)。
这些项目仅使用一种解决方案并使用静态类来处理数据层
我不喜欢依赖注入,这太复杂了,通过'f12'你只能看到接口而不是具体类
一些问题:
- 哪种模式更适合性能(快速网站)?
- 不好用“public Db db = new Db();” 在控制器中,而不是仅在域层(解决方案)中使用它?
- 使用依赖注入有什么好处?使用我的模式还不错吧?
- 将项目拆分为数据层的 2 个解决方案有什么好处?
例子:
public class LanguageController : AdminController
{
public Db db = new Db();
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
//
// GET: /Admin/Language/
public ActionResult Index()
{
return View(db.Languages.ToList());
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(short id)
{
Language language = db.Languages.Find(id);
db.Languages.Remove(language);
db.SaveChanges();
return RedirectToAction("Index");
}
...
}