forked from remogloor/Ninject.Web.WebApi
-
Notifications
You must be signed in to change notification settings - Fork 37
Dependency injection for controllers
Sean Salmon edited this page Mar 6, 2015
·
3 revisions
In the previous step we already prepared anything that is necessary for controller injection. The constructor of controllers can be changed now to accept dependencies. The only thing that has to be done is to configure the Ninject bindings for its dependencies. The controller itself will be found by Ninject even without adding a binding. Of course, you can still add a binding for the controller in case you need to specify more information for the binding (e.g. an additional constructor argument).
Here is an example of a controller that has the welcome message service as dependency.
public class ValueController : ApiController
{
private readonly IValueProvider valueProvider;
public ValueController(IValueProvider valueProvider)
{
this.valueProvider = valueProvider;
}
public IEnumerable<string> Get()
{
return this.valueProvider.GetValues();
}
}
public class WelcomeMessageServiceModule : NinjectModule
{
public override void Load()
{
this.Bind<IValueProvider>().To<ValueProvider>();
}
}