我過(guò)去使用過(guò)很多不同的DI容器,但從未使用過(guò) Unity(特別是Unity 4.0.1)。我正在使用一個(gè).NET MVC具有典型三層架構(gòu)的普通舊應(yīng)用程序。Repository -> Domain -> WebUI。我需要知道我做錯(cuò)了什么,以便我可以讓我注冊(cè)的依賴項(xiàng)在域?qū)由瞎ぷ鳌_@是我的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(我在它自己的項(xiàng)目和主項(xiàng)目的文件夾中使用):namespace WebApplication1.Services{ public class CustomerService { private readonly IUnitOfWork _uow; public CustomerService(IUnitOfWork uow) { _uow = uow; } }}現(xiàn)在,當(dāng)我嘗試CustomerService像這樣調(diào)用控制器中的類時(shí),它不起作用:public ActionResult Index(){ var service = new CustomerService(); return View();}誰(shuí)能指導(dǎo)我正確的方向,開始DI在域?qū)由瞎ぷ鳎?
為什么 Unity (DI) 在控制器中工作,但在我的服務(wù)層中不起作用?
三國(guó)紛爭(zhēng)
2023-07-22 16:39:13