Adding a Custom Method to a nopCommerce Core Service in a Plugin

In nopCommerce, you can extend a core service to include a new method and new functionality using both dependency injection and inheritance. For this example, we’ll use TaxService provided in Nop.Services.

Implementation

First, create a new interface in your plugin that inherits from the core service interface:

// ICustomTaxService.cs

using Nop.Services.Tax;

namespace YourNamespace
{
    public interface ICustomTaxService : ITaxService
    {
        void YourCustomMethod(); 
    }
}

After creating the interface, create the implementation class, inheriting from both the newly created interface and the base service:

// CustomTaxService.cs

namespace YourNamespace
{
    public class CustomTaxService : TaxService, ICustomTaxService
    {
        // constructor passing in all dependencies using base()
        public CustomTaxService(...) : base(...)
        
        public void YourCustomMethod() {
            // implementation here
        }
    }
}

Finally, make sure to connect the interface to the implementation in your plugin’s DependencyRegistrar.cs file:

class DependencyRegistrar : IDependencyRegistrar
{
    public int Order { get { return 1; } }

    public void Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config)
    {
        builder.RegisterType<CustomTaxService>().As<ICustomTaxService>();
    }
}

Usage

Once the above is created, you can reference the new service using the interface created (usually, this is done in a controller or a service):

private readonly ICustomTaxService _customTaxService;

public WarrantyTaxService(
    ICustomTaxService customTaxService
){
    _customTaxService = customTaxService;
}

// now use the service for anything you need!

Leave a Reply

Your email address will not be published. Required fields are marked *