使用 Identity 和 EF 的 MVC 應用程式。
我想使用 Unity 實作依賴注入。我已經在專案中安裝了 Unity(Unity 和 Unity.mvc5),但現在我迷失了如何實作它......到目前為止,(在更改任何內容之前)我在每個控制器中實體化 dbcontext,然后在控制器建構式中我使用 new xxxx(db) 創建服務實體。
我的控制器是這樣的:
public class SomeController : Controller {
private ApplicationDbContext db = new ApplicationDbContext("DefaultConnection");
private XxService xxService;
public SomeController() {
this.xxService = new XxService(db);
}
public ActionResult Index() {
string name = xxService.Foo(5);
return View();
}
}
然后我有我的服務:
public class XxService {
private ApplicationDbContext db;
private YyService yyService;
public XxService(ApplicationDbContext db) {
this.db = db;
this.yyService = new YyService(db);
}
public string Foo(int id) {
Customer customer = yyService.Bar(id);
return customer.Name;
}
}
public class YyService {
private ApplicationDbContext db;
public YyService(ApplicationDbContext db) {
this.db = db;
}
public Customer Bar(int id) {
return db.Customers.Find(id);
}
}
和統一配置:
public static class UnityConfig {
public static void RegisterComponents() {
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
//container.RegisterType<XxService>(new Unity.Injection.InjectionConstructor());
}
}
我真的不明白我應該在 Unity 配置中注冊什么以及如何注冊,和/或我應該創建什么介面......我應該注冊服務嗎?資料庫背景關系?兩個都?如何?一些代碼會很棒,這讓我發瘋......
uj5u.com熱心網友回復:
Unity 容器/微軟依賴注入

uj5u.com熱心網友回復:
是的,您必須將介面\具體實作對的每個注冊都放在 RegisterComponents() 中。我假設您為您的 DbContext 類定義了介面。(開發人員喜歡被補充,我們不知道嗎?;)) 所以除了注冊服務之外,您幾乎完成了所有作業:),如下所示:
var container = new UnityContainer();
container.RegisterType<IService1, Service1>(new PerRequestLifetimeManager());
container.RegisterType<IService2, Service2>(new SingletonLifetimeManager());
container.RegisterType<IMyDbContext, MyDbContext>(new PerRequestLifetimeManager(),
new InjectionConstructor("name=MyDbConnection");
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/334482.html
標籤:C# asp.net-mvc 统一3d
上一篇:Applescript谷歌翻譯
