OData Using C#, MVC, WebAPI, Entity Framework, Dependency Injection (DI)/Inversion of Control (IoC) and Kendo UI

The first thing to do is to, after adding the appropriate references, is to setup our Global.asax, and register our DI container.


public class MvcApplication : System.Web.HttpApplication
{
 protected void Application_Start()
 {
 AreaRegistration.RegisterAllAreas();

WebApiConfig.Register(System.Web.Http.GlobalConfiguration.Configuration);
 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
 RouteConfig.RegisterRoutes(RouteTable.Routes);
 BundleConfig.RegisterBundles(BundleTable.Bundles);
 GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

// DI
 Bootstrap();
 }

/// <summary>
 /// This could also be initialized using the WebActivator MVC Extension:
 /// [assembly: WebActivator.PostApplicationStartMethod(
 /// typeof(Web.App_Start.SimpleInjectorInitializer), "Initialize")]
 /// </summary>
 private static void Bootstrap()
 {
 //
 // SimpleInjector configuration
 //

// 1. Create a new Simple Injector container
 var container = new SimpleInjector.Container(); // repository

// 2. Configure/register the container

container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
 container.RegisterWebApiControllers(Assembly.GetExecutingAssembly());

container.Register<ATMS.Repository.IUnitOfWork, ATMS.Repository.UnitOfWork>();
 container.Register<ATMS.DAL.IDbContext, ATMS.DAL.AtmsContext>();


 //// 3. Optionally verify the container's configuration
 container.Verify();

//var instance = container.GetInstance<IDAL>();
 //// 4. Register the container as MVC IDependencyResolver
 DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

// perform additional registrations - Web API, SignalR, etc.
 // Register Simple Injector as Web API dependency resolver.
 GlobalConfiguration.Configuration.DependencyResolver =
 new SimpleInjectorHttpDependencyResolver(container);
 //// Register Simple Injector as SignalR dependency resolver.
 //GlobalHost.DependencyResolver = new DependencyInjection.SignalR.DependencyResolver(container);

}

<span style="line-height: 1.5;">


 

 

WebAPI / OData

Add the WebAPI references to your MVC project: http://www.nuget.org/packages/Microsoft.AspNet.WebApi.

Add the OData references to your MVC project: http://www.nuget.org/packages/Microsoft.Data.OData/.

I created an Area called API in the solution which is responsible for data access. Thus, there are two controller sections in the MVC project.

  • /Areas/API/Controllers/
    – UsersController.cs : ~/api/Users
    – UserGroupsController.cs : ~Api/UserGroups
  • /Controllers
    – UserController : ~/User/[controller action]

Since we want OData doing the URL translations we need to register the routes and entities with WebAPI. This is done inWebApiConfig.cs:


using System.Web.Http;
using System.Web.Http.OData.Builder;
using DAL;

public static class WebApiConfig
{
 public static void Register(HttpConfiguration config)
 {
 var modelBuilder = new ODataConventionModelBuilder();

// OData routes are case-sensitive; if the Uri case does not match or the EntitySet has
 // not been added, a "406 Not Acceptable" exception will be thrown

modelBuilder.EntitySet<USER>("Users");
 modelBuilder.EntitySet<USERGROUP>("UserGroups");
 var model = modelBuilder.GetEdmModel();

config.Routes.MapODataRoute(
 routeName: "OData",
 routePrefix: "api",
 model: model
 );

config.EnableQuerySupport();

config.Routes.MapHttpRoute(
 name: "DefaultApi",
 routeTemplate: "api/{controller}/{id}",
 defaults: new { id = RouteParameter.Optional }
 );

// Uncomment the following line of code to enable query support
 // for actions with an IQueryable or IQueryable<T> return type.
 // To avoid processing unexpected or malicious queries, use the
 // validation settings on QueryableAttribute to validate incoming queries.
 // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
 config.EnableQuerySupport();

// To disable tracing in your application,
 // please comment out or remove the following line of code
 // For more information, refer to: http://www.asp.net/web-api
 config.EnableSystemDiagnosticsTracing();


 config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling =
 Newtonsoft.Json.PreserveReferencesHandling.All;
 }
}

Now our data access will be done through two routes:

  • ~/api/Users
  • ~/api/UserGroups

Routes are case sensitive. You will receive the following error if the case is not matched:

  • 406 Not Acceptable
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s