Input object as lazy loading

I have MVC code as shown below. I am using nInject for IoC. Interestingly, when I hit an execute request like SendMail , a controller object is created, nInject creates subobjects for both objects with readonly: _mailSrv and _dbSrv , but I only need one variable in this request.

Is it ok to inject a variable as lazy loading. When the code needs an object, will it be created?

public class HomeController:Controller
{
    private readonly IMailService _mailSrv;
    private readonly IDatabaseService _dbSrv;

    public HomeController:Controller(IMailService mailSrv, IDatabaseService dbSrv)
    {
        _mailSrv = mailSrv;
        _dbSrv = dbSrv;
    }

    public ActionResult SendMail(string mailAddress)
    {
        _mailSrv.Do(mailAddress);
    }

    public ActionResult SaveToDatabase(int id, string data)
    {
        _dbSrv.Do(id, data);
    }
}

      

+3


source to share


2 answers


Just tried it.

Add Ninject.Extensions.Factory to your project and change the member variables to Lazy .



public class HomeController : Controller
{
    private readonly Lazy<IMailService> _mailSrv;
    private readonly Lazy<IDatabaseService> _dbSrv;

    public HomeController(Lazy<IMailService> mailSrv, Lazy<IDatabaseService> dbSrv)
    {
        _mailSrv = mailSrv;
        _dbSrv = dbSrv;
    }

    public ActionResult SendMail(string mailAddress)
    {
        _mailSrv.Value.Do(mailAddress);            
    }

    public ActionResult SaveToDatabase(int id, string data)
    {
        _dbSrv.Value.Do(id, data);            
    }
}

      

Instances are now lazy.

+4


source


Hmm, Not sure about ninject, but usually not, you will get object instances when you instantiate the controller.

Alternatives:

Make two controllers (I suggest this)

Entering Objects, Not Objects

Personally, this is not for me, I think the IoC container should be your factory.



public ActionResult SendMail(string mailAddress)
    {
        _mailSrvFactory.Create().Do(mailAddress);
    }

      

Directly bind an object in a method, not inject

This is usually considered "bad" because you have to loop the IoC container around

public ActionResult SendMail(string mailAddress)
    {
        kernel.Get<IMailServer>().Do(mailAddress);
    }

      

I think looking at it on a deeper level. Perhaps you can create a custom scope that actually wrapped the class in a factory in the same way that IoC containers can expose classes as monochromatic. I need to think about it though

+2


source







All Articles