Unity.MVC4 lazy is not working in ASP.NET MVC app

后端 未结 2 1356
面向向阳花
面向向阳花 2020-12-11 06:21

I am using ASP.NET MVC 4 application.

Home controller’s constructor is parameterized with 2 parameter(Iservice1 service1, Iservice2 service2) Not all the code path u

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 06:51

    Since I don't know how exactly to implement the lazy loading on DI registration level, I'm often using this way to lazy load services. I would share my approach with you.

    Each service interface will inherit the IService interface which is base for all service interfaces.

    public interface IService
    {
        // I just want to be sure I'm instantiating ONLY services types.
        // This is my base interface 
    }
    
    public interface IMyService : IService
    {
        void DoSomeWork();
    }
    

    Then, every service will implement his own interface:

    public class MyService : IMyService
    {
        public void DoSomeWork()
        {
            // Some action performed.
        }
    }
    

    My abstract BaseController class implements this logic

    public abstract class BaseController : Controller
    {
        public T LoadService() where T : IService
        {
            return (T)System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(T));
        }
    }
    

    And finally, in my controller which inherits the BaseController I would be able to do this:

    public class TestController : BaseController
    {
        // Only parameterless constructor exists created by the compiler.
    
        [HttpPost]
        public ActionResult PerformWork()
        {
            var testService = LoadService();
            testService.DoSomeWork();
    
            return View();
        }
    }
    

    I'm curious to see better implementations for lazy loading services or get to know how to implement lazy loading on types registration level using Unity or Ninject.

提交回复
热议问题