using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Ninject;
using NinjectAdapter;
using FirstWebAPI.Models;
namespace FirstWebAPI
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class WebApiApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
}
}
}
This is the global.asax for the app. Its the default that gets generated.
Bilal Hasan ...
Member
4 Points
5 Posts
WebAPI DI with Ninject throws error for ILogger
Mar 04, 2012 04:01 PM|LINK
Hi,
I am trying to implement DI using Ninject. My code is as follows, (I had a look on what was posted by Shawn Wildermuth here).
public static class NinjectMVC3 { private static readonly Bootstrapper bootstrapper = new Bootstrapper(); /// <summary> /// Starts the application /// </summary> public static void Start() { DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule)); DynamicModuleUtility.RegisterModule(typeof(HttpApplicationInitializationModule)); bootstrapper.Initialize(CreateKernel); } /// <summary> /// Stops the application. /// </summary> public static void Stop() { bootstrapper.ShutDown(); } /// <summary> /// Creates the kernel that will manage your application. /// </summary> /// <returns>The created kernel.</returns> private static IKernel CreateKernel() { var kernel = new StandardKernel(); //var locator = ; RegisterServices(kernel); //GlobalConfiguration.Configuration.ServiceResolver.SetResolver(t => locator.GetInstance(t),t=>locator.GetAllInstances(t)); GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new NinjectServiceLocator(kernel)); return kernel; } /// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { kernel.Bind<IProductRepository>().To<ProductRepository>(); kernel.Bind<IHttpControllerActivator>().To<DefaultHttpControllerActivator>(); kernel.Bind<IHttpControllerFactory>().To<DefaultHttpControllerFactory>(); kernel.Bind<IFormatterSelector>().To<FormatterSelector>(); } } }davebettin
Member
313 Points
94 Posts
Re: WebAPI DI with Ninject throws error for ILogger
Mar 05, 2012 05:17 AM|LINK
What does your global.asax look like? Is this being used in a MVC3 app?
@dbettin
awebb
Member
204 Points
91 Posts
Re: WebAPI DI with Ninject throws error for ILogger
Mar 05, 2012 07:36 AM|LINK
Try this:-
Comment out your service locator statement, uncomment the line above it, and change it to this:-
Notice the use of TryGet instead of Get - i.e. it will return null for those types it doesn't know about instead of throwing.
Bilal Hasan ...
Member
4 Points
5 Posts
Re: WebAPI DI with Ninject throws error for ILogger
Mar 05, 2012 09:42 PM|LINK
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Ninject; using NinjectAdapter; using FirstWebAPI.Models; namespace FirstWebAPI { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class WebApiApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); BundleTable.Bundles.RegisterTemplateBundles(); } } }davebettin
Member
313 Points
94 Posts
Re: WebAPI DI with Ninject throws error for ILogger
Mar 06, 2012 02:12 AM|LINK
Yeah, awebb is right. An exception is being thrown when it trys to resolve the service in Ninject.
Here is a sample ninject resolver: https://github.com/ChristianWeyer/Thinktecture.Web.Http/blob/master/Thinktecture.Web.Http/DI/NinjectResolver.cs.
@dbettin
Bilal Hasan ...
Member
4 Points
5 Posts
Re: WebAPI DI with Ninject throws error for ILogger
Mar 12, 2012 12:34 AM|LINK
This post from Phil Haack solved my problem
.
http://haacked.com/archive/2012/03/11/itrsquos-the-little-things-about-asp-net-mvc-4.aspx
discofunk
Member
3 Points
1 Post
Re: WebAPI DI with Ninject throws error for ILogger
Mar 30, 2012 05:48 PM|LINK
I made a simple IDepenedencyResolver adapter for Ninject. Seems to work:
public class NinjectDependencyResolverAdapter : IDependencyResolver { private readonly IKernel kernel; public NinjectDependencyResolverAdapter(IKernel kernel) { this.kernel = kernel; } #region Implementation of IDependencyResolver public object GetService(Type serviceType) { return kernel.TryGet(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { return kernel.GetAll(serviceType); } #endregion }Then it's just:
Bilal Hasan ...
Member
4 Points
5 Posts
Re: WebAPI DI with Ninject throws error for ILogger
May 04, 2012 01:42 PM|LINK
Does it work with Web API or MVC 4.
Because the same thing failed for me with WebAPI. I was using the MVC 4 beta release.