Inject dependency into WebApiConfig class in ASP.NET Web Api using Ninject

by sunil ravulapalli /31. August 2013 01:46 /asp.net-web-api /Comments (0)


First you have to make the WebApiConfig into a non static class as shown below.
Notice, that the dependency I want to be inject is IAccountsService.

public class WebApiConfig
{
	private static IAccountsService _accountsService;
	public WebApiConfig(IAccountsService accountsService)
	{
		_accountsService = accountsService;
	}

	public void Register(HttpConfiguration config)
	{
		var authentication = CreateAuthenticationConfiguration();
		config.MessageHandlers.Add(new AuthenticationHandler(authentication));

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

		config.EnableSystemDiagnosticsTracing();
	}

	private AuthenticationConfiguration CreateAuthenticationConfiguration()
	{
		var authentication = new AuthenticationConfiguration
		{
			RequireSsl = false,
			EnableSessionToken = true
		};

		// Basic Authentication
		authentication.AddBasicAuthentication(_accountsService.ValidateAccountUsingSiteCredential);

		return authentication;
	}
}

Now, in the Global.asax file modify the Application_Start as follows

protected void Application_Start()
{
	AreaRegistration.RegisterAllAreas();

	//WebApiConfig.Register(GlobalConfiguration.Configuration);
	DependencyResolver.Current.GetService<WebApiConfig>().Register(GlobalConfiguration.Configuration);
	FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
	RouteConfig.RegisterRoutes(RouteTable.Routes);
	BundleConfig.RegisterBundles(BundleTable.Bundles);
}

That's it! You are good to go!

blog comments powered by Disqus