Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ninject with Membership.Provider

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?

like image 311
lancscoder Avatar asked Nov 08 '10 10:11

lancscoder


3 Answers

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>();
like image 140
mare Avatar answered Oct 10 '22 17:10

mare


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.

like image 39
lancscoder Avatar answered Oct 10 '22 15:10

lancscoder


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.

like image 37
Ian Davis Avatar answered Oct 10 '22 15:10

Ian Davis