【问题标题】:Constructor injection in MVC 3MVC 3 中的构造函数注入
【发布时间】:2011-03-16 22:22:19
【问题描述】:

我的控制器中有这段代码:

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 config 中的注入依赖是:

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

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

来源错误:

在执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常起源和位置的信息。

堆栈跟踪:

[MissingMethodException: 否 定义为的无参数构造函数 这个对象。]
System.RuntimeTypeHandle.CreateInstance(RuntimeType 类型,布尔型 publicOnly,布尔型 noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal&ctor, 布尔值& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(布尔 publicOnly,布尔型 skipCheckThis, 布尔填充缓存)+98
System.RuntimeType.CreateInstanceDefaultCtor(布尔 publicOnly,布尔值 skipVisibilityChecks,布尔值 skipCheckThis,布尔填充缓存)+241 System.Activator.CreateInstance(类型 类型,布尔非公共)+69
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext,类型控制器类型) +67

我需要 ASP.NET MVC 3 和 razor 引擎来调用参数化构造函数。

【问题讨论】:

    标签: .net c#-4.0 asp.net-mvc-3 dependency-injection unity-container


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      相关资源
      最近更新 更多