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
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.