2017-10-22 60 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

回答