Default MembershipProvider could not be found
I recently had an issue writing an MVC 4 application with the
following parts:
- Custom MembershipProvider
- StructureMap Dependency Injection container via the Nuget package StructureMap.MVC4
- IMembershipService interface
- The purpose of this is to wrap up the MembershipProvider to make it testable.
I wired up the dependencies for my application in the
IoC.Initialize() method:
This method (and class) was placed in my application by the
StructureMap.MVC4
NuGet package mentioned earlier.
The constructor of the Account Controller looks like this:
The IMembershipService dependency should be injected by StructureMap
defined in the Initialize method above.\
\
However, when I run my code I get the following:\
\
No parameterless constructor defined for this object.
This error is saying that StructureMap was unable to load the
AccountController as there was not a parameterless constructor
available. I found this odd, as I have defined one constructor and had
setup StructureMap appropriately to inject the dependency. I
searched around for a solution for this and found
this.
Essentially, you have to tell StructureMap which Membership provider to
use:
But, I still got the following error:
This was the final piece of the puzzle. The StructureMap.MVC4 NuGet
package added a file called StructureMapMvc.cs into the
App_Start folder. This file uses the PreApplicationStartMethod
to fire the static Start method within the class. I figured that it
may be firing too early and the Membership.Provider property was not
yet populated (if someone is able to confirm this, that would be great).
I removed the PreApplicationStartMethod attribute and instead called
the Start method directly from the Global.asax.
It all started working great after that.