Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection with Custom Membership Provider

I have an ASP.NET MVC web application that implements a custom membership provider. The custom membership provider takes a UserRepository to its constructor that provides an interface between the membership provider and NHibernate. The UserRepository is provided by the Ninject IoC container.

Obviously, however, this doesn't work when the provider is instantiated by .NET: the parameterless constructor does not have a UserRepository and cannot create one (the UserRepository requires an NHibernate session be passed to its constructor), which then means that the provider cannot access its data store. How can I resolve my object dependency?

It's probably worth noting that this is an existing application that has been retrofitted with Ninject. Previously I used parameterless constructors that were able to create their required dependencies in conjunction with the parametered constructors to assist unit testing.

Any thoughts, or have I built myself into a corner here?

like image 862
alastairs Avatar asked May 02 '10 12:05

alastairs


3 Answers

Correct answer from Michael B. from: Dependency injection and ASP.Net Membership Providers

You can obtain your repository (or service) injection in this way:

public IRepository Repository { get { return DependencyResolver.Current.GetService(IRepository ); } }
like image 157
Donald Avatar answered Nov 08 '22 12:11

Donald


You might want to keep the parameterless constructor, that initializes the needed repositories using Ninject. You might want to use the Common Service Locator, so you won't need to have neither a reference to Ninject nor it's container inside your custom provider. It seems Ninject doesn't have an official an adapter implementation for CSL, but writing one shouldn't be to hard (check the other implementations, like Windsor's), and I'm sure there's an unofficial implementation somewhere.

like image 5
SztupY Avatar answered Nov 08 '22 11:11

SztupY


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 4
Ian Davis Avatar answered Nov 08 '22 11:11

Ian Davis