Revisiting the Factory pattern
In the Strategy pattern example, we implemented a solution that instantiated 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 look at a few rewrites of the Strategy project using factories to explore some possibilities.
Project – Factory
Let’s start by mixing a factory with method injection and injecting the view model directly into our method instead of injecting IHomeService
. To achieve this, we rewrite the Index
method of the HomeController
class to 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...