3

我知道這是一個重複的問題,但我無法找到我的錯誤的答案。 我想表明我的房間保存在數據庫中的表,但我得到一個錯誤:沒有無參數的構造函數對象定義

Server Error in '/' Application. 
    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) +98 
    System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241 
    System.Activator.CreateInstance(Type type, Boolean nonPublic) +69 
    System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +67 

    [InvalidOperationException: An error occurred when trying to create a controller of type 'HotelProjectFinal.Controllers.RoomController'. Make sure that the controller has a parameterless public constructor.] 
    System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182 
    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) +232 
    System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49 
    System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13 
    System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 
    System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 
    System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124 
    System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98 
    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() +8969412 
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 

但我有一個構造函數withou參數:

namespace HotelProjectFinal.Controllers 
{ 
    public class RoomController : Controller 
    { 
     private IRoomRepository repository; 

     public RoomController(IRoomRepository roomRepository) 
     { 
      repository = roomRepository; 
     } 

     public ViewResult List() 
     { 
      return View(repository.Rooms); 
     } 
    } 
} 

我的看法是:

@model IEnumerable<HotelProjectFinal.Models.Room> 

    @{ 
    ViewBag.Title = "List"; 
    } 

    @foreach (var p in Model) 
    { 
     <div class="item"> 
     <h3>@p.Room_number</h3> 
     @p.Room_Type 
     <h4>@p.Room_Type.Price.ToString("c")</h4> 
     </div> 
     } 

我使用ninject:

   public class NinjectControllerFactory : DefaultControllerFactory 
      { 
    private IKernel ninjectKernel; 
    public NinjectControllerFactory() 
    { 
     ninjectKernel = new StandardKernel(); 
     AddBindings(); 
    } 
    protected override IController GetControllerInstance(RequestContext requestContext, 
    Type controllerType) 
    { 
     return controllerType == null 
     ? null 
     : (IController)ninjectKernel.Get(controllerType); 
    } 
    private void AddBindings() 
    { 
     ninjectKernel.Bind<IRoomRepository>().To<EFRoomRepository>(); 
    } 
      } 
      } 
+1

您使用的是IoC容器嗎? 「IRoomRepository」如何被注入? – 2012-03-28 21:37:40

+5

在您的示例控制器中,我只看到一個接受1個參數的構造函數。 – 2012-03-28 21:38:47

+0

你說你有一個沒有參數的構造函數....它在哪裏?看來你唯一的構造函數需要一個IRoomRepository。 – 2012-03-28 21:39:42

回答

4

你已經有了一個控制器工廠,但事實上堆棧跟蹤沒有提到Ninject,這表明你忘記了告訴MVC它。

你可以通過添加一行來解決這個問題。

但是,推薦的做法是將Ninject掛入adding a NuGet reference to Ninject.MVC3。在關聯的Ninject MVC3 wiki上有文檔。

3

請嘗試更改您的構造函數如下:

public RoomController() { } // You were missing this parameterless constructor 

[Inject] 
public RoomController(IRoomRepository roomRepository) 
{ 
    repository = roomRepository; 
} 

Ninject正在尋找一個參數的構造函數,因爲你沒有指定[進樣上面,你希望使用依賴注入的構造函數。這混淆了「Ninject」並導致拋出異常。

The primary DI pattern is Constructor Injection. When activating an instance of a type Ninject will choose one of the type’s constructors to use by applying the following rules in order:-

  • If a constructor has an [Inject] attribute, it is used (but if you apply the attribute to more than one, Ninject will throw a NotSupportedException at runtime upon detection).
  • If no constructors have an [Inject] attribute, Ninject will select the one with the most parameters that Ninject understands how to resolve.
  • If no constructors are defined, Ninject will select the default parameterless constructor (assuming there is one).

的更多信息可在這裏找到:

https://github.com/ninject/ninject/wiki/Injection-Patterns

如魯指出的那樣,[進樣]屬性污染與外部的擔憂控制器。

This ties your code to a specific container. (Although Ninject does permits the customization of the specific attribute to look for, the point remains – you’re polluting an interface with external concerns.)

您的實際問題可能依賴於缺少參考Ninject.MVC3

+1

無參數構造函數沒有任何作用,只是在這裏增加了混淆。如果wiki不夠清楚,可能應該採用粗體和斜體 - 將[Inject]屬性放在不是一個好的總體思路上 - 它無緣無故地把你綁定到一個容器,並且完成任何事情。你能否改變你的建議,以消除兩者的建議。 – 2012-03-29 07:41:06

+0

感謝您指出這一點,我已更新該帖子。 – 2012-03-29 08:05:37

+0

很酷,謝謝.... – 2012-03-29 12:20:05

2

即使IRoomRepository 可能爲空,不使它成爲一個參數的構造函數。一開始,看起來你的IoC沒有正確連接到IRoomRepository。如果沒有IoC或錯誤配置的IoC,則控制器激活程序會爲您的控制器查找無參數構造函數。

// This is a parameterless constructor. 
public RoomController() 
{ } 

// This is not a parameterless constructor. 
public RoomController(IRoomRepository roomRepository) 
{ 
    repository = roomRepository; 
} 

編輯,你使用Ninject.Mvc和你的基礎MvcHttpApplication是否實現NinjectHttpApplication?

相關問題