我過去使用過很多不同的DI容器,但從未使用過 Unity(特別是Unity 4.0.1)。我正在使用一個.NET MVC具有典型三層架構的普通舊應用程序。Repository -> Domain -> WebUI。我需要知道我做錯了什么,以便我可以讓我注冊的依賴項在域層上工作。這是我的global.asax.protected void Application_Start(){ // ... IUnityContainer container = new UnityContainer(); RegisterDependencies(container); DependencyResolver.SetResolver(new WebApplicationDependencyResolver(container));}protected void RegisterDependencies(IUnityContainer container){ container.RegisterType<IUnitOfWork, UnitOfWork>();}這是WebApplicationDependencyResolver上面使用的:namespace WebApplication1.Infrastructure{ public class WebApplicationDependencyResolver : IDependencyResolver { private IUnityContainer _container; public WebApplicationDependencyResolver(IUnityContainer container) { _container = container; } public object GetService(Type serviceType) { try { return _container.Resolve(serviceType); } catch (Exception) { return null; } } public IEnumerable<object> GetServices(Type serviceType) { try { return _container.ResolveAll(serviceType); } catch (Exception) { return null; } } }}我的Domain Layer類CustomerService.cs(我在它自己的項目和主項目的文件夾中使用):namespace WebApplication1.Services{ public class CustomerService { private readonly IUnitOfWork _uow; public CustomerService(IUnitOfWork uow) { _uow = uow; } }}現在,當我嘗試CustomerService像這樣調用控制器中的類時,它不起作用:public ActionResult Index(){ var service = new CustomerService(); return View();}誰能指導我正確的方向,開始DI在域層上工作?
1 回答

ABOUTYOU
TA貢獻1812條經驗 獲得超5個贊
嘗試在控制器中注入服務而不是注入IUnitOfWork. 然后在控制器方法中使用服務實例:
public HomeController(CustomerService service)
{
_service = service
}
public ActionResult Index()
{
var model = _service.GetAllCustomers();
return View(model);
}
這應該可行,但讓你的類依賴于另一個類并不是一個好主意。依賴關系應該是一個契約(接口)。您應該重構CustomerService以提取接口ICustomerService并將其注入控制器中。然后你需要在方法中將其注冊到容器中RegisterDependencies:
container.RegisterType<ICustomerService, CustomerService>();
- 1 回答
- 0 關注
- 138 瀏覽
添加回答
舉報
0/150
提交
取消