Constructor injection in MVC 3
I have this code in my controller:
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")
});
}
and the injection dependencies in web config is:
<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>
When I run the application the error is :
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.CreateIns开发者_如何学PythontanceDefaultCtor(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
I need the ASP.NET MVC 3 and razor engine to call the parametrized constructor.
You need to implement the IDependencyResolver
interface. Once you do this you can use dependency injection anywhere within a MVC 3 application, even views (although property injection only).
精彩评论