Lazy Dependency Injection

前端 未结 3 1321
一个人的身影
一个人的身影 2020-12-08 21:30

I have a project where the Ninject is used as IoC container. My concern is that a lot of classes have such kind of constructors:

[Inject]
public HomeControll         


        
3条回答
  •  遥遥无期
    2020-12-08 21:52

    You can also inject into an action method with the syntax below. (I'm not sure exactly what version this was introduced).

    Constructor is best practice, but I had to do this once deliberately when I had a service that was doing some expensive initialization - accidentally in fact - but it wasn't discovered for a while and it was just easiest to move it to the one method that did need it.

    This can make for cleaner code if you only need to access a service from one action method - but bear in mind if you inject it to the method you'll have to pass it around everywhere because it will no longer be on this. Definitely don't go assigning to this.service in an action method - that's horrible.

    public IActionResult About([FromServices] IDateTime dateTime)
    {
        ViewData["Message"] = "Currently on the server the time is " + dateTime.Now;
    
        return View();
    }
    

    https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection?view=aspnetcore-2.2#action-injection-with-fromservices

提交回复
热议问题