I setup a CustomRoleProver as:
public class CustomRoleProvider : RoleProvider
{
private readonly IRepository<User> _repository;
public CustomRoleProvider(IRepository<User> repository)
{
_repository = repository;
}
...
In my Global.asax.cs I have:
//Create Ninject DI kernel
var kernel = new StandardKernel();
kernel.Bind<IRepository<User>>().To<Repository<User>>();
//Tell ASP.NET MVC 3 to use our Ninject DI Container
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
When I try to run my code I get:
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: No parameterless constructor defined for this object.
Source Error:
Line 64:
Line 65:
Line 66:
Line 67:
Line 68:
So maybe I have a totally incorrect understanding of DI and ninject. I thought that when it tried to instantiate teh CustomRoleProvider it would create the user repository and pass it to the constructor not trying to use a parameterless one.
Do I understand this incorrectly or is my setup just incorrect?
I find this strange because the DI seems to be mostly working for the controllers.
You’re writing a roleprovider, but these are not currently DI aware. A lot of the classes in MVC are DI aware, which is why you see it workign with controllers.
To be able to inject a constructor parameter the DI container has to be responsible for creating the object you’re hoping to inject into. Just registering a type does not magically make it locatable.
With roleproviders, it is the Roles class within the framework that create instances of the providers, including your custom provider. It only works parameterless constructors. You’ll need to use something like property injection within your custom provider and use Roles.Provider to get the instance to inject your dependencies into.