亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 Unity (DI) 在控制器中工作,但在我的服務層中不起作用?

為什么 Unity (DI) 在控制器中工作,但在我的服務層中不起作用?

C#
三國紛爭 2023-07-22 16:39:13
我過去使用過很多不同的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>();


查看完整回答
反對 回復 2023-07-22
  • 1 回答
  • 0 關注
  • 138 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號