我一直在ASP.NET MVC中使用依賴注入的方式,我已經在下面的代碼中解釋,但我不知道如果這是正確的和標準的方式來做到這一點。所以我只想知道我在做什麼是錯誤的,或者是否有更好更專業的方式來做到這一點。在ASP.NET MVC依賴注入
public interface IService {
public Boolean AddRecord(Object _Model);
}
public class Employee: IService {
DataBase Context = new DataBase();
public Boolean AddRecord(Object _Model) {
Context.Add((EmployeeModel) _Model);
return Context.SaveChanges() != 0;
}
}
public class DataController: Controller {
IService service;
public DataController(IService service) {
this.service = service;
}
public ActionResult AddRecord(Object _Model, String Caller) {
if (service.Add(_Model)) {
TempData["Result"] = "Data Added";
return RedirectToAction(Caller);
}
TempData["Result"] = "Please try again";
return View (Caller, _Model);
}
}
當我想用用DI控制器,我做的:(這是要消耗DataController類正道)
public class TestController: Controller {
public ActionResult Index() {
return View();
}
public ActionResult TestIt (EmployeeModel _Model) {
DataController DC = new DataController(new Employee());
return DC.AddRecord(_Model, "../Test/TestIt");
}
}
您已經在DataController中注入了一個依賴項。對於其他控制器來說,同樣的事情,我的意思是,不要在其他控制器中實例化DataController,而只需在構造函數中放置依賴關係。 – 2014-08-30 12:25:26
當然,請看下面的答案。 – 2014-08-30 12:32:35
你有下面的概念 - 依賴注入/反轉正是你在這裏展示的。另一方面,控制反轉是你下一步應該研究的。有很多容器爲你提供這個 - 有些甚至直接插入到MVC中(我們使用Ninject)。控制反轉不需要你完全實例化你的依賴關係。 – 2014-08-30 13:06:47