0

我有这样的代码在我的控制器:在MVC构造方法注入3

public class IssueController : BaseController, IIssueController 
{ 

    #region Members 

    IPublicationsManagementService publicationService; 

    #endregion 

    #region Constructors 

     public IssueController(IPublicationsManagementService publicationService) 
     { 
      this.publicationService = publicationService; 
     } 

    #endregion 

    public ActionResult IssueSearch() 
    { 

     return View(new IssueSearchViewModel() 
     { 
      Magazines 
       = new SelectList(publicationService.GetAllProducts(), "Id", "Name") 
     }); 
    } 

,并在web配置注入的依赖是:

<register type="Infoquality.PSMS.Presentation.Web.MVC.Client.Controllers.IIssueController, PSMS.Presentation.Web.MVC.Client" 
    mapTo="Infoquality.PSMS.Presentation.Web.MVC.Client.Controllers.IssueController, PSMS.Presentation.Web.MVC.Client"> 
      <lifetime type="PerWebRequest" /> 
      <constructor> 
      <param name="publicationService"> 
       <dependency name="sd"/> 
      </param> 
      </constructor> 

<register type="Infoquality.PSMS.Application.Publications.PublicationsManagement.IPublicationsManagementService, PSMS.Application.Publications" 
    mapTo="Infoquality.PSMS.Application.Publications.PublicationsManagement.PublicationsManagementService, PSMS.Application.Publications" 
        name="sd"> 
      <lifetime type="singleton" /> 
     </register> 

当我运行应用程序的错误是:

源错误:

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.

堆栈跟踪:

[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

我需要的ASP.NET MVC 3剃须刀引擎调用参数化的构造函数。

回答

1

您需要实现IDependencyResolver接口。一旦你这样做了,你可以在MVC 3应用程序中的任何地方使用依赖注入,甚至是视图(尽管只是属性注入)。