Scope
Scenario
Normally, we will create a widget plugin to do that, nice and neat that plugin is isolated from the page controller and allow easy plug and play. This would work fine for most people.
However, in certain scenarios, if the works required to be done in the controller is more complicated like introducing new services, security control etc, then we will need to modify the controller.
The gotcha is we don't want to change the existing controller for future upgrade, with IoC and OO architecture, one would think it is easy just to create a new controller to inherit from the existing controller for custom works, but life is not that easy.
Customization
CoreController
In CustomerController, we need to set the Register() as virtual. And that is only change required in our core controller, so that you can override its functionalities.CustomController
Let's take CustomerController as an example and I want to override the Register().I created my own CustomerController file inside a folder called Custom.
I gave it a namespace of Nop.Web.Controllers.Custom, and inherit from the Nop.Web.Controllers.CustomController.
You will need to set your constructor same as the parent controller, and use the keyword base to inherit from the base controller, pretty standard C# inheritance syntax.
You may override the Register() like the following. In this example, we changed the value of the ViewBag.Title only, but as you can imagine, you can initialize new objects or call other services, all be achieved.
RouteProvider
In the Nop.Web project, Infrastructure\RouteProvider.cs, we need to map the controller to a different namespace, so our custom controller will be used in place of the parent one.
View
For demonstration purpose, I updated the view as follow, but a more professional way by using theme can be found here.Result
Compile the solution and head to register page, it should look like this.IoC
What about IoC? How will the CustomController get instantiated? That is already handled by the Nop.Web.Framework.DependencyRegistrar that will register all controllers in the assembly.
very helpful, thank you!
ReplyDelete