IMPORTANT: This version of Sitefinity CMS is out of support and the respective product documentation is no longer maintained and can be outdated. Use the version selector to view a supported product version.
One of the most common patterns in programming is the Inversion of Control (IoC) design pattern. Feather provides a smooth integration of Ninject Dependency Injection (DI) framework and gives you the ability to use the IoC pattern when working with ASP.NET Web API.
The advantages of using the IoC design pattern are the following:
The following article demonstrates how to use Dependency Injection for the constructor of a Web API controller. To achieve this, you create a custom Web API controller and define its constructor parameters via the Ninject API.
Ninject is a lightweight dependency injection framework for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software’s architecture, your code becomes easier to write, reuse, test, and modify.
PREREQUISITES: You must have installed Feather 1.4.410.0 or above.
Ninject.Web.WebApi.WebHost
Ninject.Web.WebApi
public interface IAnimalService
{
//define your service methods here
}
public class AnimalService: IAnimalService
//implement your service methods here
~/Mvc/Controllers
PetController
public class PetController : ApiController
public PetController(SitefinityWebApp.Mvc.Services.IAnimalService animalService)
public string Get()
return "Rabbit";
NinjectWebCommon
App_Start/NinjectWebCommon.cs
RegisterServices
kernel.Bind<
IAnimalService
>().To<
AnimalService
>();
Global.asax
protected void Application_Start(object sender, EventArgs e)
Telerik.Sitefinity.Abstractions.Bootstrapper.Initialized += Bootstrapper_Initialized;
void Bootstrapper_Initialized(object sender, Telerik.Sitefinity.Data.ExecutedEventArgs e)
if (e.CommandName == "Bootstrapped")
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
RESULT: You are able to access your custom Web API controller by requesting localhost/api/Pet URL in a browser.
localhost/api/Pet
Back To Top
To submit feedback, please update your cookie settings and allow the usage of Functional cookies.
Your feedback about this content is important