Autofac.Core.Activators.Reflection.DefaultConstructorFinder Cannot resolve parameter 'Nop.Services.Orders.IVoucherService

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
10 лет назад
using Nop ver 3.1
I am trying to add a new service called VoucherService and ImportVoucherManager in Nop.Services.orders and I get the following error when I try to open Admin area.

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Nop.Admin.Controllers.VoucherCodesController' can be invoked with the available services and parameters:
Cannot resolve parameter 'Nop.Services.Orders.IVoucherService voucherService' of constructor 'Void .ctor(Nop.Services.Orders.IVoucherService, Nop.Services.Security.IPermissionService, Nop.Services.Helpers.IDateTimeHelper, Nop.Services.ExportImport.IImportVoucherManager)'.
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: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Nop.Admin.Controllers.VoucherCodesController' can be invoked with the available services and parameters:
Cannot resolve parameter 'Nop.Services.Orders.IVoucherService voucherService' of constructor 'Void .ctor(Nop.Services.Orders.IVoucherService, Nop.Services.Security.IPermissionService, Nop.Services.Helpers.IDateTimeHelper, Nop.Services.ExportImport.IImportVoucherManager)'.

Source Error:


Line 167:        public object ResolveOptional(Type serviceType)
Line 168:        {
Line 169:            return Scope().ResolveOptional(serviceType);
Line 170:        }
Line 171:        


Source File: c:\Visual Studio 2012Projects\PssNop31\Libraries\Nop.Core\Infrastructure\DependencyManagement\ContainerManager.cs    Line: 169

Stack Trace:


[DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Nop.Admin.Controllers.VoucherCodesController' can be invoked with the available services and parameters:
Cannot resolve parameter 'Nop.Services.Orders.IVoucherService voucherService' of constructor 'Void .ctor(Nop.Services.Orders.IVoucherService, Nop.Services.Security.IPermissionService, Nop.Services.Helpers.IDateTimeHelper, Nop.Services.ExportImport.IImportVoucherManager)'.]
   Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) +528
   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) +242
   Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType, IEnumerable`1 parameters) +72
   Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType) +48
   Nop.Core.Infrastructure.DependencyManagement.ContainerManager.ResolveOptional(Type serviceType) in c:\Visual Studio 2012Projects\PssNop31\Libraries\Nop.Core\Infrastructure\DependencyManagement\ContainerManager.cs:169
   Nop.Web.Framework.Mvc.NopDependencyResolver.GetService(Type serviceType) in c:\Visual Studio 2012Projects\PssNop31\Presentation\Nop.Web.Framework\Mvc\NopDependencyResolver.cs:12
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +41

[InvalidOperationException: An error occurred when trying to create a controller of type 'Nop.Admin.Controllers.VoucherCodesController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +179
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +197
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +49
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Below is my Code for Voucherservices

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nop.Core;
using Nop.Data;
using Nop.Core.Data;
using Nop.Core.Domain.Orders;
using Nop.Services.Events;


namespace Nop.Services.Orders
{
    public partial class VoucherService : IVoucherService
    {
        private readonly IRepository<VoucherCodes> _voucherRepository;
        private readonly IDbContext _context;
        private readonly IEventPublisher _eventPublisher;

        public VoucherService(IRepository<VoucherCodes> voucherRepository, IDbContext context, IEventPublisher eventPublisher)
        {
            this._eventPublisher = eventPublisher;
            this._context = context;
            this._voucherRepository = voucherRepository;

        }

        /// <summary>
        /// Get all vouchers in table
        /// </summary>
        /// <param name="voucherNumber"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="showHidden"></param>
        /// <returns></returns>
        public virtual IPagedList<VoucherCodes> GetAllVoucherCodes(int pageIndex, int pageSize, bool showHidden = false)
        {
            var query = _voucherRepository.Table;


            var vouchers = new PagedList<VoucherCodes>(query, pageIndex, pageSize);
            return vouchers;
        }

        /// <summary>
        /// Gets a voucher entry from voucher table by vouchernumber
        /// </summary>
        /// <param name="voucherNumber"></param>
        /// <returns></returns>

        public virtual void InsertVoucher(VoucherCodes voucher)
        {
            if (voucher == null)
                throw new ArgumentException("voucher");
            _voucherRepository.Insert(voucher);

            //event notification
            _eventPublisher.EntityInserted(voucher);
        }

        public virtual void UpdateVoucher(VoucherCodes voucher)
        {
            if (voucher == null)
                throw new ArgumentNullException("voucher");

            _voucherRepository.Update(voucher);

            //event notification
            _eventPublisher.EntityUpdated(voucher);
        }

        public virtual void DeleteVoucher(VoucherCodes voucher)
        {
            if (voucher == null)
                throw new ArgumentNullException("voucher");

            _voucherRepository.Delete(voucher);

            //event notification
            _eventPublisher.EntityDeleted(voucher);
        }

        public virtual VoucherCodes GetVoucherByVoucherNumber(string vouchernumber)
        {
            if (String.IsNullOrEmpty(vouchernumber))
                return null;

            vouchernumber = vouchernumber.Trim();

            var query = from p in _voucherRepository.Table
                        orderby p.Id
                        where p.VoucherNumber == vouchernumber
                        select p;
            var Voucher = query.FirstOrDefault();
            return Voucher;
        }

    }
}

this is the code for ImportVoucherManager

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nop.Services.Orders;
using OfficeOpenXml;
using Nop.Core;
using Nop.Core.Domain.Orders;

namespace Nop.Services.ExportImport
{
    public partial class ImportVoucherManager: IImportVoucherManager
    {
       private readonly ICheckoutAttributeService _CheckoutAttributeService;
       private readonly IVoucherService _VoucherService;
      
       public ImportVoucherManager(ICheckoutAttributeService checkoutAttributeServervice,IVoucherService voucherService)
        {
            this._CheckoutAttributeService = checkoutAttributeServervice;
            this._VoucherService = voucherService;
        }
        protected virtual int GetColumnIndex(string[] properties, string columnName)
        {

            if (properties == null)
                throw new ArgumentNullException("properties");

            if (columnName == null)
                throw new ArgumentNullException("columnName");

            for (int i = 0; i < properties.Length; i++)
                if (properties[i].Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
                    return i + 1; //excel indexes start from 1
            return 0;
        }

        public virtual IEnumerable<CheckoutAttribute> Getid(string v)
        {
           return Getid(v).Where(x => x.Name == v);
            
          
        }

        /// <summary>
        /// Import products from XLSX file
        /// </summary>
        /// <param name="stream">Stream</param>
        public virtual void ImportVouchersFromXlsx(Stream stream)
        {
            // ok, we can run the real code of the sample now
            using (var xlPackage = new ExcelPackage(stream))
            {
                // get the first worksheet in the workbook
                var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault();
                if (worksheet == null)
                    throw new NopException("No worksheet found");

                //the columns
                var properties = new string[]
                {
                    "voucherNumber",
                    "partner",
                    "purchaseDate",
                };


                int iRow = 2;
                while (true)
                {
                    bool allColumnsAreEmpty = true;
                    for (var i = 1; i <= properties.Length; i++)
                        if (worksheet.Cells[iRow, i].Value != null && !String.IsNullOrEmpty(worksheet.Cells[iRow, i].Value.ToString()))
                        {
                            allColumnsAreEmpty = false;
                            break;
                        }
                    if (allColumnsAreEmpty)
                        break;

                    string voucherNumber = worksheet.Cells[iRow, GetColumnIndex(properties, "VoucherNumber")].Value as string;
                    int tv = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductTemplateId")].Value);
                    var myid = Getid(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductTemplateId")].Value.ToString()).Select(x => x.Id);
                    int partnerId = Convert.ToInt32(myid);
                    DateTime purchaseDate = Convert.ToDateTime(worksheet.Cells[iRow, GetColumnIndex(properties, "PurchaseDate")].Value);




                    var nvoucher = _VoucherService.GetVoucherByVoucherNumber(voucherNumber);
                    bool isnewvoucher = false;
                    if (nvoucher == null)
                    {
                        isnewvoucher = true;
                    }
                    var voucher = new VoucherCodes();
                    voucher.VoucherNumber = voucherNumber;
                    voucher.PurchaseDate = purchaseDate;
                    voucher.PartnerId = partnerId;
                    if (isnewvoucher)
                    {
                        _VoucherService.InsertVoucher(voucher);
                    }





                    ////next Voucher
                    iRow++;
                }
            }
        }
    }
}

and this is the code for the controller

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Nop.Admin.Models.Orders;
using Nop.Core.Domain.Cms;
using Nop.Core.Domain.Orders;
using Nop.Services.Helpers;
using Nop.Services.Configuration;
using Nop.Services.Security;
using Nop.Services.Orders;
using Nop.Web.Framework;
using Nop.Web.Framework.Controllers;
using Nop.Services.ExportImport;
using Telerik.Web.Mvc;


namespace Nop.Admin.Controllers
{
    public partial class VoucherCodesController : BaseNopController
    {
        private readonly IPermissionService _permissionService;        
        private readonly IDateTimeHelper _dateTimeHelper;
        private readonly IImportVoucherManager _ImportVoucherManager;
        private readonly IVoucherService _voucherService;

        public VoucherCodesController(IVoucherService voucherService, IPermissionService permissionService, IDateTimeHelper dateTimeHelper, IImportVoucherManager importVoucherManager)
        {
            this._dateTimeHelper = dateTimeHelper;
            this._ImportVoucherManager = importVoucherManager;
            this._permissionService = permissionService;
            this._voucherService = voucherService;
        
        }
        //
        // GET: /VoucherCodes/

        public ActionResult Index()
        {
          return   RedirectToAction("List");
        }

        //
        // GET: /VoucherCodes/Details/5

        public ActionResult List()
        {

            if (!_permissionService.Authorize(StandardPermissionProvider.ManageOrders))
                return AccessDeniedView();

            var model = new VoucherCodesModel();
            return View(model);
        }

        [HttpPost, GridAction(EnableCustomBinding = true)]
        public ActionResult VoucherList(GridCommand command, VoucherCodesModel model)
        {
            if(_permissionService.Authorize(StandardPermissionProvider.ManageOrders))
                return AccessDeniedView();

            var vouchers = _voucherService.GetAllVoucherCodes( 0, 40, true);
            var gridModel = new GridModel<VoucherCodesModel>
            {

                Data = vouchers.Select(x =>
                    {
                        var m = x.ToModel();
                        m.PurchaseDate = _dateTimeHelper.ConvertToUserTime( x.PurchaseDate,DateTimeKind.Utc);
                        return m;

                    }),
                Total = vouchers.TotalCount
            };


            return new JsonResult
            {
                //   Data = GridModel;
            };
        }

        public ActionResult Details(int id)
        {
            return View();
        }



        //
        // GET: /VoucherCodes/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /VoucherCodes/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /VoucherCodes/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /VoucherCodes/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /VoucherCodes/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /VoucherCodes/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

for some reason Autofac will not bind the voucherServices.cs or ImportVoucherManager.cs

any suggestions
10 лет назад
Did you register dependency?
10 лет назад
Thank you, I found that about an hour after I posted this.
6 лет назад
How did you resolve this issue? can you please explain here?
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.