Revisiting the Factory pattern
In the Strategy pattern example, we implemented a solution that instantiated a HomePageViewModel
using the new
keyword. While doing that is acceptable, we could use method injection instead, mixed with the use of a factory. The Factory patterns are handy tools when the time comes to construct objects. Let's take a look at a few rewrites using factories to explore some possibilities.
Factory mixed with method injection
Our first option would be to inject the view model directly into our method instead of injecting IHomeService
. To achieve this, let's rewrite the HomeController
class like this:
public class HomeController : Controller { public IActionResult Index([FromServices]HomePageViewModel viewModel) { return View(viewModel); } // Omitted Privacy() and Error() }
The FromServicesAttribute
class tells the ASP.NET Core pipeline to inject an instance of HomePageViewModel
directly into the method.
Now that...