2017-10-22 10 views
0

インターフェイスを実装しようとしましたが、次のエラーで問題が発生しています:C#MVCインターフェイスエラー

コードを階層化して、良いプラクティスを使用しようとしています。私はまた、インターフェイスを使用して、新しいコードでもっと実験したいと思っています。私はこれを働かせることができますように願っています。

私はこのエラーに関する記事がありますので、私はそれらを検討したことを知っています。私はInterfacesとNuGet Packagesの初心者であるため、実装するのが混乱しているものがあります。私は私の質問が、すべての私の将来の発展のための基礎として服用することができ、私の授業への完全な例や修正を加えた簡単な回答を開発できることを願っています。ここで

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を使用する予定のDependency InjectionフレームワークをASP.NET MVCでUnity Frameworkを使用して設定する記事を持っています。 URL: - https://www.codeproject.com/Articles/1199400/Dependency-Injection-using-Uni​​ty-Framework-with-AS – Saineshwar

答えて

0

YAYYY !!!! :)

だから、私は正しいことを持っている場合には、依存関係を注入するAutofacを使用しています。このリンク>https://levelnis.co.uk/blog/dependency-injection-with-autofac#ck_modal

を使用して指示に従いました。

Autofacを実装した後、私のプロジェクトは現在、1つのパラメータコンストラクタとインタフェースで動作しますが、通常と呼ばれている:)