Pages - Menu

nopCommerce - Custom Service inherit from Core Service by Dependency Injection and new interface

Scope

Previously I was doing customization to override a method in custom class from core class. It provided the cleanest way to inherit from nopCommerce core services without any tampering to the core files. One thing that I couldn't do with the previous approach is to create new method or to overload a method. Today, we will go through this implementation.

Implementation

To begin with, we will create a new custom interface, and put the new methods (or overloading methods) that we need. The custom interface will inherit from the core interface.


The Custom class will implement the core class and inherit from the custom interface instead of the usual core interface. This part is quite crucial as we will see in a minute. Don't forget your usual ctor.



From my calling class (in this example, I am using a custom class of the ImportManager), instead of the usual property assignment, we will need to cast the concrete class to the custom interface, so it can be assigned to the private / protected property.


In IoC, we will need to register the custom class for the core interface!!


Wait a minute, how does it work? Shouldn't I register as custom interface? If you do, you will get an error, when there are other core classes that are still using the core interface with the private property still referencing the core interface. Something like a ctor doesn't match up exception.

The fact that custom class implement custom interface but custom interface also inherit from core interface, we created this chain in polymorphism that if I am a type of RacingCar, then I must be a type of Car. That's why the explicit cast in  _productService = (TAProductService) productService; would work.

Build the solution and run the code, my new method is being called.


Conclusion

As you can see, this is not very difficult but a little tricky when we are dealing with IoC and MVC at the same time. As demonstrated, it only required a little code to do the work.

Talking about racing cars, who went to the 2013 Sydney 500 Super Car last week?





3 comments:

  1. can you send me the proper code as here i am not able to understand the pictures that you have given ie which class which core.. Please help

    ReplyDelete
    Replies
    1. and also it is saying that object doesnot contain a constructor that takes 1 argument

      Delete
  2. Great way to reduce code duplication, thank you for sharing!

    ReplyDelete