I'm new to Ninject and I'm having problems using it with a custom membership provider.
My membership provider has a repository interface passed in. It looks like:
public class CustomMembershipProvider : MembershipProvider
{
public CustomMembershipProvider( IRepository repository )
{
}
}
I'm using the code thats part of the Account Model in the MVC app as a starting point.
However when it calls Membership.Provider
I get an error saying No parameterless constructor defined for this object
.
I've setup the bindings in ninject to bind a IRepository
to a Repository
class which work as I've testing this in a controller.
What are the correct bindings in Ninject to use for Membership.Provider
?
This is how it should be done today with new versions of both MVC and Ninject (version 3):
You have access to the DependencyResolver instance and Ninject sets itself as the current DependencyResolver. That way you don't need hacks to get access to the static Ninject kernel. Please note, my example uses my own IUserService repository for Membership...
IUserService _userService = DependencyResolver.Current.GetService<IUserService>();
The best solution I found was the following:
private IRepository _repository;
[Inject]
public IRepository Repository
{
get { return _repository; }
set { _repository= value; }
}
public CustomMembershipProvider()
{
NinjectHelper.Kernel.Inject(this);
}
Where NinjectHelper is a static helper class to get the Kernal from.
Since the membership collection and the Membership.Provider
instance are created before Ninject can instantiate them, you need to perform post creation activation on the object. If you mark your dependencies with [Inject]
for your properties in your provider class, you can call kernel.Inject(Membership.Provider)
- this will assign all dependencies to your properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With