2017-10-22 64 views
0

我試圖實現接口,並遇到以下錯誤的困難:C#MVC接口錯誤

我想代碼分層,並試圖使用良好的做法。我也想開始使用接口並用新代碼進行更多的實驗。希望我能得到這個工作。

我知道有許多關於所以這個錯誤的文章,我已經探索了他們。有些困惑,我實現,因爲我與接口和封裝的NuGet一個初學者。我希望我的問題可以開發出一個完整的例子或修正我的課,我可以和我所有的未來發展的基地使用一個簡單的答案。

No parameterless constructor defined for this object. 
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: System.MissingMethodException: No parameterless constructor defined for this object. 

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. 

Stack Trace: 


[MissingMethodException: No parameterless constructor defined for this object.] 
    System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0 
    System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113 
    System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232 
    System.Activator.CreateInstance(Type type, Boolean nonPublic) +83 
    System.Activator.CreateInstance(Type type) +6 
    System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55 

[InvalidOperationException: An error occurred when trying to create a controller of type 'UniStock.Controllers.InventoryController'. Make sure that the controller has a parameterless public constructor.] 
    System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178 
    System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +77 
    System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +66 
    System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +191 
    System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50 
    System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48 
    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 

這裏是我的課:

控制器:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

using UniStock.Services.ExportImport; 


namespace UniStock.Controllers 
{ 
    public partial class InventoryController : Controller 
    { 
     #region Fields 

     private readonly IImportManager _importService; 

     #endregion 

     #region Constructors 


     public InventoryController(IImportManager importService) 
     { 
      this._importService = importService; 
     } 

     #endregion 


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

     [HttpGet] 
     public ActionResult ImportNewCodes() 
     { 
      var model = new UniStock.Models.InventoryModel(); 

      return PartialView(model); 
     } 

     [HttpPost] 
     public JsonResult ImportNewCodesPost(FormCollection form) 
     { 
      try 
      { 
       var file = Request.Files["excelFile"]; 
       if (file != null && file.ContentLength > 0) 
       { 
        string filepath = _importService.ImportNewCodes(file.InputStream); 

        return Json(new 
        { 
         success = false, 
         message = filepath 
        }); 
       } 
       else 
       { 
        return Json(new 
        { 
         success = false, 
         message = "file not selected" 
        }); 
       } 
      } 
      catch (Exception ex) 
      { 
       return Json(new 
       { 
        success = false, 
        message = "ImportNewCodesPost: " + ex.Message 
       }); 
      } 

      return Json(new 
      { 
       success = false, 
       message = "Email is invalid" 
      }); 
     } 
    } 
} 

型號:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

namespace UniStock.Models 
{ 
    public partial class InventoryModel 
    { 
     public InventoryModel() 
     { 
     } 

     public int InventoryID { get; set; } 

     public string Code { get; set; } 

     public string Description { get; set; } 

     public string Style { get; set; } 

     public string SytleColour { get; set; } 

     public string ColourCode { get; set; } 

     public string ColourName { get; set; } 

     public string Size { get; set; } 

     public string BarCode { get; set; } 

     public bool? Active { get; set; } 

     public bool? Deleted { get; set; } 

     public DateTime? DateCreated { get; set; } 

     public DateTime? DateUpdated { get; set; } 

     public string CreatedBy { get; set; } 

     public string UpdatedBy { get; set; } 
    } 
} 

庫存服務:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace UniStock.Services.Inventory 
{ 
    public partial class InventoryService 
    { 
     public InventoryService() { } 
    } 
} 

庫存服務接口:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace Services.Inventory 
{ 
    public partial interface IInventoryService 
    { 
    } 
} 

進口服務:

using System; 
using System.IO; 
using System.Linq; 
using System.Web; 

using OfficeOpenXml; 

using System.Data; 
using System.Data.SqlClient; 
using System.Data.OleDb; 
using System.Configuration; 

using Services.Inventory; 

namespace UniStock.Services.ExportImport 
{ 
    /// <summary> 
    /// Import manager 
    /// </summary> 
    public partial class ImportManager : IImportManager 
    { 
     #region Fields 

     private readonly IInventoryService _inventoryService; 

     #endregion 

     #region Ctor 

     public ImportManager(IInventoryService inventoryService) 
     { 
      this._inventoryService = inventoryService; 
     } 

     #endregion 

     #region Utilities 

     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; 
     } 

     protected virtual string ConvertColumnToString(object columnValue) 
     { 
      if (columnValue == null) 
       return null; 

      return Convert.ToString(columnValue); 
     } 

     protected virtual string GetMimeTypeFromFilePath(string filePath) 
     { 
      //var mimeType = MimeMapping.GetMimeMapping(filePath); 

      ////little hack here because MimeMapping does not contain all mappings (e.g. PNG) 
      //if (mimeType == "application/octet-stream") 
      // mimeType = "image/jpeg"; 

      //return mimeType; 

      return ""; 
     } 

     #endregion 

     #region Methods 

     public DataTable LoadFromExcelFile(string filePath) 
     { 
      String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath); 
      //Create Connection to Excel work book 
      using (OleDbConnection excelConnection = new OleDbConnection(excelConnString)) 
      { 
       //Create OleDbCommand to fetch data from Excel - you can query the sheet as if it were a sql table effectively 
       using (OleDbCommand cmd = new OleDbCommand("SELECT [SKU],[0-199],[200-499],[500-999],[1000+] from [Sheet1$]", excelConnection)) 
       { 
        excelConnection.Open(); 
        using (OleDbDataReader dReader = cmd.ExecuteReader()) 
        { 
         DataTable myData = new DataTable(); 
         myData.Load(dReader); 
         return myData; 
        } 
       } 
      } 

      return null; 
     } 


     public virtual string ImportNewCodes(Stream stream) 
     { 
      try 
      { 
       using (var xlPackage = new ExcelPackage(stream)) 
       { 
        //get the first worksheet in the workbook 
        var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); 
        if (worksheet == null) 
         return "No worksheet found"; 

        return "file accessed"; 
       } 
      } 
      catch (Exception ex) 
      { 
       return ex.Message; 
      } 
     } 

     #endregion 
    } 
} 

進口服務接口:

using System.IO; 

namespace UniStock.Services.ExportImport 
{ 
    /// <summary> 
    /// Import manager interface 
    /// </summary> 
    public partial interface IImportManager 
    { 

     string ImportNewCodes(Stream stream); 


    } 
} 
+0

框架試圖創建控制器,但它不會出現依賴注入是設置?不這樣做,它預計在控制器上一個空的構造,但你的控制器有一個參數。因此,無論Di不會設置,或者如果它是,這個接口/類型可能不正確映射... –

+0

你能幫助我建立這個依賴注入?我是一個絕對新的蜜蜂:/ – Orion

+0

哪個依賴注入框架你要使用Unity或Ninject,我有一篇關於使用ASP.NET MVC設置使用Unity Framework的依賴注入的文章。網址: - https://www.codeproject.com/Articles/1199400/Dependency-Injection-using-Uni​​ty-Framework-with-AS – Saineshwar

回答