ASP.NET Core DependencyResolver

后端 未结 7 722
故里飘歌
故里飘歌 2020-12-15 19:20

In ASP.NET MVC 5 is possible to obtain some dependency through DependencyResolver.Current.GetService(). Is there something similar in ASP.NET Core?

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 19:34

    Here is the way that worked for me in .Net core 2.0

    public ViewResult IndexWithServiceLocatorPattern([FromServices]ProductTotalizer totalizer)
    {
        var repository = (IRepository)HttpContext.RequestServices.GetService(typeof(IRepository));
        ViewBag.HomeController = repository.ToString();
        ViewBag.Totalizer = totalizer.repository.ToString();
        return View("Index", repository.Products);
    }
    

    If I have to do it with classical way, It would be like below.

    public class HomeController : Controller
    {
        private readonly IRepository repo;
    
        /// 
        /// MVC receives an incoming request to an action method on the Home controller. 
        /// MVC asks the ASP.NET service provider component for a new instance of the HomeController class.
        /// The service provider inspects the HomeController constructor and discovers that it has a dependency on the IRepository interface. 
        /// The service provider consults its mappings to find the implementation class it has been told to use for dependencies on the IRepository interface. 
        /// The service provider creates a new instance of the implementation class. 
        /// The service provider creates a new HomeController object, using the implementation object as a constructor argument.
        /// The service provider returns the newly created HomeController object to MVC, which uses it to handle the incoming HTTP request.
        /// 
        /// 
        public HomeController(IRepository repo)
        {
            this.repo = repo;
        }
    
        /// 
        ///  Using Action Injection
        ///  MVC uses the service provider to get an instance of the ProductTotalizer class and provides it as an
        ///  argument when the Index action method is invoked.Using action injection is less common than standard
        ///  constructor injection, but it can be useful when you have a dependency on an object that is expensive to
        ///  create and that is required in only one of the action methods defined by a controller
        /// 
        /// 
        /// 
        public ViewResult Index([FromServices]ProductTotalizer totalizer)
        {
            ViewBag.Total = totalizer.repository.ToString();
            ViewBag.HomeCotroller = repo.ToString();
            return View(repo.Products);
        }
    }
    

提交回复
热议问题