How to get override GetFinalPrice from plugin

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
9 years ago
Hello All,

How to get override GetFinalPrice in plugin. I have put below code in plugin but price is not overried.

  public override decimal GetFinalPrice(Product Product, Customer customer, decimal additionalCharge,
                                              bool includeDiscounts, int quantity)
        {
            // If the plugin is not installed, just use the regular pricing service
            if (!PreciousMetalsPricingProvider.IsPluginInstalled)
                return base.GetFinalPrice(Product, customer, additionalCharge, includeDiscounts, quantity);

            // get the PreciousMetals detail for this product
            var detail = this._preciousMetalsDetailService.Get(Product.Id);

            // if there is none, just use the regular pricing service
            if (detail == null)
                return base.GetFinalPrice(Product, customer, additionalCharge, includeDiscounts, quantity);

            // get the piece price
            var initialPrice = GetMetalTierPrice(Product, customer, quantity, detail);

            //discount + additional charge (just like the original PriceCalculationService)
            decimal result;
            if (includeDiscounts)
            {
                Discount appliedDiscount;
                var discountAmount = GetDiscountAmount(Product, customer, additionalCharge, quantity,
                                                       out appliedDiscount);
                result = initialPrice + additionalCharge - discountAmount;
            }
            else
            {
                result = initialPrice + additionalCharge;
            }
            if (result < decimal.Zero)
                result = decimal.Zero;

            // return the total price
            return result;
        }



Please help me.
9 years ago
Assume you have created a class that implements IPriceCalculationService, and in this class, you had an override method as you stated.

The next step is you need to create your DependencyRegistrar and does something like this.

builder.RegisterType<MyPriceCalculationService>().As<IPriceCalculationService>();
9 years ago
Hello sunnyw,

Thank you for reply.

I have register server in DependencyRegistrar in my pluging but now i am getting below error.


Server Error in '/' Application.
Circular component dependency detected: Nop.Web.Controllers.CatalogController -> Nop.Web.Controllers.CatalogController -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsProductService -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsProductService -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsPriceCalculationService -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsPriceCalculationService -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsProductService.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Autofac.Core.DependencyResolutionException: Circular component dependency detected: Nop.Web.Controllers.CatalogController -> Nop.Web.Controllers.CatalogController -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsProductService -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsProductService -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsPriceCalculationService -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsPriceCalculationService -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsProductService.

Source Error:


Line 6:          @Html.Widget("home_page_top")
Line 7:          @Html.Action("TopicBlock", "Topic", new { systemName = "HomePageText" })
Line 8:          @Html.Action("HomepageCategories", "Catalog")
Line 9:          @Html.Action("HomepageProducts", "Product")
Line 10:         @Html.Action("HomepageBestSellers", "Product")


Source File: e:\MyProjects\nopCommerce_3.40_Source\Presentation\Nop.Web\Views\Home\Index.cshtml    Line: 8

Stack Trace:


[DependencyResolutionException: Circular component dependency detected: Nop.Web.Controllers.CatalogController -> Nop.Web.Controllers.CatalogController -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsProductService -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsProductService -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsPriceCalculationService -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsPriceCalculationService -> Nop.Plugin.Pricing.PreciousMetals.Services.PreciousMetalsProductService.]
   Autofac.Core.Resolving.CircularDependencyDetector.CheckForCircularDependency(IComponentRegistration registration, Stack`1 activationStack, Int32 callDepth) +431
   Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +158
   Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +72
   Autofac.Core.Activators.Reflection.<>c__DisplayClass2.<CanSupplyValue>b__0() +82
   Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate() +233
   Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) +563
   Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) +109
   Autofac.Core.Resolving.InstanceLookup.Execute() +158
   Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +282
   Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +72
   Autofac.Core.Registration.<>c__DisplayClass8.<RegistrationsFor>b__3(IComponentContext c, IEnumerable`1 p) +57
   Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) +191
   Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) +109
   Autofac.Core.Resolving.InstanceLookup.Execute() +158
   Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +282
   Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +72
   Autofac.Core.Activators.Reflection.<>c__DisplayClass2.<CanSupplyValue>b__0() +82
   Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate() +233
   Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) +563
   Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) +109
   Autofac.Core.Resolving.InstanceLookup.Execute() +158
   Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +282
   Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +72
   Autofac.Core.Registration.<>c__DisplayClass8.<RegistrationsFor>b__3(IComponentContext c, IEnumerable`1 p) +57
   Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) +191
   Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) +109
   Autofac.Core.Resolving.InstanceLookup.Execute() +158
   Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +282
   Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +72
   Autofac.Core.Activators.Reflection.<>c__DisplayClass2.<CanSupplyValue>b__0() +82
   Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate() +233
   Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) +563
   Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) +109
   Autofac.Core.Resolving.InstanceLookup.Execute() +158
   Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +282
   Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +72
   Autofac.Core.Registration.<>c__DisplayClass8.<RegistrationsFor>b__3(IComponentContext c, IEnumerable`1 p) +57
   Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) +191
   Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) +109
   Autofac.Core.Resolving.InstanceLookup.Execute() +158
   Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +282
   Autofac.Core.Resolving.ResolveOperation.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +60
   Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) +111
   Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +278
   Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) +175
   Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters) +243
   Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType, IEnumerable`1 parameters) +72
   Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType) +48
   Autofac.Integration.Mvc.AutofacDependencyResolver.GetService(Type serviceType) +57
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +87

[InvalidOperationException: An error occurred when trying to create a controller of type 'Nop.Web.Controllers.CatalogController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +247
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +438
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +257
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +326
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +157
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
   System.Web.Mvc.<>c__DisplayClass7.<BeginProcessRequest>b__6() +81
   System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +69
   System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +169
   System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +2019
   System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +76
   System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +28
   System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +19
   System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +985
   System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +112
   System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName) +46
   ASP._Page_Views_Home_Index_cshtml.Execute() in e:\MyProjects\nopCommerce_3.40_Source\Presentation\Nop.Web\Views\Home\Index.cshtml:8
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +271
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +122
   System.Web.WebPages.StartPage.RunPage() +63
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +100
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +131
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +321
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9690172
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34009
9 years ago
Its an Autofac problem you can google "How to handle circular references with Autofac" to search for solution in your case.
9 years ago
Hello Lucho,


Thanks for response.

I have goggling for this issue. I think something is missing in DependencyRegistrar. below is my DependencyRegistrar.


using Autofac;
using Autofac.Core;
using Autofac.Integration.Mvc;
using Nop.Core.Data;
using Nop.Core.Infrastructure;
using Nop.Core.Infrastructure.DependencyManagement;
using Nop.Data;
using Nop.Plugin.Pricing.PreciousMetals.Data;
using Nop.Plugin.Pricing.PreciousMetals.Domain;
using Nop.Plugin.Pricing.PreciousMetals.Services;
using Nop.Services.Catalog;
using Nop.Services.Orders;
using Nop.Web.Framework.Mvc;

namespace Nop.Plugin.Pricing.PreciousMetals
{
    public class DependencyRegistrar : IDependencyRegistrar
    {
        const string objectContextName = "nop_object_context_preciousmetals_pricing";

      

        public void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            //data layer
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            const string objectContextName = "nop_object_context_preciousmetals_pricing";

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                //register named context
                builder.Register<IDbContext>(c => new PreciousMetalsPricingObjectContext(dataProviderSettings.DataConnectionString))
                    .Named<IDbContext>(objectContextName)
                   .InstancePerLifetimeScope();

                builder.Register(c => new PreciousMetalsPricingObjectContext(dataProviderSettings.DataConnectionString))
                    .InstancePerLifetimeScope();
            }
            else
            {
                //register named context
                builder.Register<IDbContext>(c => new PreciousMetalsPricingObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .Named<IDbContext>(objectContextName)
                    .InstancePerLifetimeScope();

                builder.Register(c => new PreciousMetalsPricingObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .InstancePerLifetimeScope();
            }

            // register custom objects
            builder.RegisterType<EfRepository<PreciousMetalsDetail>>()
                .As<IRepository<PreciousMetalsDetail>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>(objectContextName))
              .InstancePerLifetimeScope();

            builder.RegisterType<EfRepository<PreciousMetalsQuote>>()
                .As<IRepository<PreciousMetalsQuote>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>(objectContextName))
               .InstancePerLifetimeScope();


            //Register services
            builder.RegisterType<PreciousMetalsDetailService>().As<IPreciousMetalsDetailService>().InstancePerLifetimeScope();
            builder.RegisterType<PreciousMetalsQuoteService>().As<IPreciousMetalsQuoteService>().InstancePerLifetimeScope();
            builder.RegisterType<PreciousMetalsPriceCalculationService>().As<IPriceCalculationService>().InstancePerLifetimeScope();
            builder.RegisterType<PreciousMetalsOrderTotalCalculationService>().As<IOrderTotalCalculationService>().InstancePerLifetimeScope();
            builder.RegisterType<PreciousMetalsProductService>().As<IProductService>().InstancePerLifetimeScope();

        }


        public int Order
        {
            get { return 1; }
        }
    }
}


Please tell me which code missing here.

Thanks in Advance..
9 years ago
Hello All,

I have register service like below.


            builder.RegisterType<PreciousMetalsPriceCalculationService>().As<IPriceCalculationService>().SingleInstance().PreserveExistingDefaults();
            builder.RegisterType<PreciousMetalsOrderTotalCalculationService>().As<IOrderTotalCalculationService>().SingleInstance().PreserveExistingDefaults();
            builder.RegisterType<PreciousMetalsProductService>().As<IProductService>().SingleInstance().PreserveExistingDefaults();


but debug point is not hited on below method from plugin.

   public override decimal GetFinalPrice(Product Product,
            Customer customer,
            decimal additionalCharge = decimal.Zero,
            bool includeDiscounts = true,
            int quantity = 1)
        {
            // If the plugin is not installed, just use the regular pricing service
            if (!PreciousMetalsPricingProvider.IsPluginInstalled)
                return base.GetFinalPrice(Product, customer, additionalCharge, includeDiscounts, quantity);

            // get the PreciousMetals detail for this product
            var detail = this._preciousMetalsDetailService.Get(Product.Id);

            // if there is none, just use the regular pricing service
            if (detail == null)
                return base.GetFinalPrice(Product, customer, additionalCharge, includeDiscounts, quantity);

            // get the piece price
            var initialPrice = GetMetalTierPrice(Product, customer, quantity, detail);

            //discount + additional charge (just like the original PriceCalculationService)
            decimal result;
            if (includeDiscounts)
            {
                Discount appliedDiscount;
                var discountAmount = GetDiscountAmount(Product, customer, additionalCharge, quantity,
                                                       out appliedDiscount);
                result = initialPrice + additionalCharge - discountAmount;
            }
            else
            {
                result = initialPrice + additionalCharge;
            }
            if (result < decimal.Zero)
                result = decimal.Zero;

            // return the total price
            return result;
        }


Please help me..
9 years ago
(1) I think you already know you are getting circular reference and you know what it is. The correct solution is that your plugin should not be referencing web project. Similar to Nop.Services, web project or the controller is the consumer.

(2) The order in your DependencyRegistrar should not be 1, it needs to be a bigger number so it will register after the original PriceCalculationService is registered. Make it 10 or something.
9 years ago
sunnyw wrote:
(1) I think you already know you are getting circular reference and you know what it is. The correct solution is that your plugin should not be referencing web project. Similar to Nop.Services, web project or the controller is the consumer.



Thank you for your quick response.

but if we do not reference our plugin with Web project, how would it override the "getfinalprice" from the plugin.


Thank you in advance!
9 years ago
tech2globe wrote:
(1) I think you already know you are getting circular reference and you know what it is. The correct solution is that your plugin should not be referencing web project. Similar to Nop.Services, web project or the controller is the consumer.



Thank you for your quick response.

but if we do not reference our plugin with Web project, how would it override the "getfinalprice" from the plugin.


Thank you in advance!


PriceCalculationService.GetFinalPrice() is in the Service layer not Web layer. You just need to reference Nop.Services.
9 years ago
Thank you for more information


I have already reference add of "Nop.Services" in my plugin.


can you check once in my service because maybe missing something in my services. Services code is below.



using System;
using System.Linq;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Discounts;
using Nop.Core.Domain.Orders;
using Nop.Plugin.Pricing.PreciousMetals.Domain;
using Nop.Services.Catalog;
using Nop.Services.Directory;
using Nop.Services.Discounts;
using Nop.Core.Caching;

namespace Nop.Plugin.Pricing.PreciousMetals.Services
{
    public class PreciousMetalsPriceCalculationService : PriceCalculationService
    {
        private readonly IPreciousMetalsDetailService _preciousMetalsDetailService;
        private readonly IPreciousMetalsQuoteService _preciousMetalsQuoteService;
        private readonly IMeasureService _measureService;

        public PreciousMetalsPriceCalculationService(
            IWorkContext workContext,
             IStoreContext storeContext,
            IDiscountService discountService,
            ICategoryService categoryService,
            IProductAttributeParser productAttributeParser,
            IProductService productService,
            ICacheManager cacheManager,
            ShoppingCartSettings shoppingCartSettings,
            CatalogSettings catalogSettings,
            IPreciousMetalsDetailService preciousMetalsDetailService,
            IPreciousMetalsQuoteService preciousMetalsQuoteService,
            IMeasureService measureService)
            : base(workContext,storeContext, discountService, categoryService, productAttributeParser,productService,cacheManager, shoppingCartSettings, catalogSettings)
        {
            _preciousMetalsDetailService = preciousMetalsDetailService;
            _preciousMetalsQuoteService = preciousMetalsQuoteService;
            _measureService = measureService;
        }

        public decimal GetMetalTierPrice(Product Product, Customer customer, int quantity, PreciousMetalsDetail detail)
        {
            // get the price per piece
            var piecePrice = GetMetalPiecePrice(detail);

            if (Product.TierPrices == null || Product.TierPrices.Count == 0 ||
                (PreciousMetalsTierPriceType)detail.TierPriceType == PreciousMetalsTierPriceType.DoNotUse)
                return piecePrice;

            var tierPrices = Product.TierPrices.OrderBy(tp => tp.Quantity).ToList().FilterForCustomer(customer);

            var previousQty = 1;
            var previousPrice = piecePrice;
            foreach (var tierPrice in tierPrices)
            {
                //check quantity
                if (quantity < tierPrice.Quantity)
                    continue;
                if (tierPrice.Quantity < previousQty)
                    continue;

                //save new price
                previousPrice = tierPrice.Price;
                previousQty = tierPrice.Quantity;
            }

            // If there is no matching tier price, return the default single piece price
            if (previousQty == 1)
                return piecePrice;

            // Calculate tier prices based on type
            switch ((PreciousMetalsTierPriceType)detail.TierPriceType)
            {
                case PreciousMetalsTierPriceType.Percentage:
                    return piecePrice - ((piecePrice / 100m) * previousPrice);
                case PreciousMetalsTierPriceType.PriceDiscount:
                    return piecePrice - previousPrice;
                case PreciousMetalsTierPriceType.DoNotUse:
                    return piecePrice;
                default:
                    throw new ArgumentException("Invalid Tier Price Type!");
            }
        }

        public override decimal GetFinalPrice(Product Product, Customer customer, decimal additionalCharge,
                                              bool includeDiscounts, int quantity)
        {
            // If the plugin is not installed, just use the regular pricing service
            if (!PreciousMetalsPricingProvider.IsPluginInstalled)
                return base.GetFinalPrice(Product, customer, additionalCharge, includeDiscounts, quantity);

            // get the PreciousMetals detail for this product
            var detail = this._preciousMetalsDetailService.Get(Product.Id);

            // if there is none, just use the regular pricing service
            if (detail == null)
                return base.GetFinalPrice(Product, customer, additionalCharge, includeDiscounts, quantity);

            // get the piece price
            var initialPrice = GetMetalTierPrice(Product, customer, quantity, detail);

            //discount + additional charge (just like the original PriceCalculationService)
            decimal result;
            if (includeDiscounts)
            {
                Discount appliedDiscount;
                var discountAmount = GetDiscountAmount(Product, customer, additionalCharge, quantity,
                                                       out appliedDiscount);
                result = initialPrice + additionalCharge - discountAmount;
            }
            else
            {
                result = initialPrice + additionalCharge;
            }
            if (result < decimal.Zero)
                result = decimal.Zero;

            // return the total price
            return result;
        }

        /// <summary>
        /// This will return the metal price for the product variant's weight in the primary shop's currency
        /// </summary>
        /// <param name="detail"></param>
        /// <returns></returns>
        public decimal GetMetalPiecePrice(PreciousMetalsDetail detail)
        {

            // get the quote for this metal
            var quote = _preciousMetalsQuoteService.GetQuote((PreciousMetalType)detail.MetalType);

            // determine the unit price
            decimal unitPrice;
            switch ((PreciousMetalsQuoteType)detail.QuoteType)
            {
                case PreciousMetalsQuoteType.Bid:
                    unitPrice = quote.Bid;
                    break;
                case PreciousMetalsQuoteType.Ask:
                    unitPrice = quote.Ask;
                    break;
                case PreciousMetalsQuoteType.Low:
                    unitPrice = quote.Low;
                    break;
                case PreciousMetalsQuoteType.High:
                    unitPrice = quote.High;
                    break;
                default:
                    throw new ArgumentException("Invalid Quote Type!");
            }

            var weight = detail.Weight;
            if (detail.WeightId > 0) // assume zero means no conversion
            {
                // the unit price is per troy ounce, so convert the detail weight to troy ounces.
                var weightFrom = _measureService.GetMeasureWeightById(detail.WeightId);
                var weightTo = _measureService.GetMeasureWeightBySystemKeyword("troyounce");

                weight = _measureService.ConvertWeight(detail.Weight, weightFrom, weightTo, false);
            }

            // the piece price starts from the unit price times the weight
            var piecePrice = unitPrice * weight;

            // figure the markup
            var markup = 0m;
            switch ((PreciousPriceCalculationType)detail.MathType)
            {
                case PreciousPriceCalculationType.AddFirstThenMultiply:
                    markup = ((piecePrice + detail.FlatMarkup) * detail.PercentMarkup / 100m);
                    break;
                case PreciousPriceCalculationType.MultiplyFirstThenAdd:
                    markup = (piecePrice * detail.PercentMarkup / 100m) + detail.FlatMarkup;
                    break;
                default:
                    goto case PreciousPriceCalculationType.MultiplyFirstThenAdd;
            }

            // add the markup to the piece price
            piecePrice += markup;


            if (detail.PriceRounding > 0)
            {
                switch ((PriceRoundingType)detail.PriceRoundingType)
                {
                    case PriceRoundingType.RoundDown:
                        piecePrice = Math.Floor(piecePrice / (decimal)detail.PriceRounding) * ((decimal)detail.PriceRounding);
                        break;
                    case PriceRoundingType.RoundUp:
                        piecePrice = Math.Ceiling(piecePrice / (decimal)detail.PriceRounding) * ((decimal)detail.PriceRounding);
                        break;
                }
            }


            // return the price, but nothing less than the LowerAmount
            return detail.LowerAmount > piecePrice ? detail.LowerAmount : piecePrice;
        }
    }
}
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.