Geeks With Blogs

News profile for Aligned at Stack Overflow, Q&A for professional and enthusiast programmers

Donate Bitcoins

Check out Elapser from T3rse!
"free in Christ Jesus from the law of sin and death." Romans 8:2 (ESV) Check out the Falling Plates video on YouTube.
more about the Gospel
And then listen to Francis Chan speaking at LifeLight in SD.

Programming and Learning from SD

If you try to dependency injection into a constructor with WebAPI, you’ll get an exception that says you need a parameter less constructor. The same is true for MVC controllers, but that is a different topic. Microsoft contains a good guide on how to get this working. There is also a useful StructureMap.DependencyResolver nuget package  by statish860 that does it for you.

Get the nuget package, then add
GlobalConfiguration.Configuration.DependencyResolver = new DependencyResolver(ObjectFactory.Container); to the Application_Start method in your Global.asax. Then you’ll be able to inject into your API controller like so:

public class AdministrationApiController : ApiController
{
  /// <summary>
  /// The administration service.
  public class AdministrationApiController : ApiController
  {
  /// </summary>
  private readonly IAdministrationService administrationService;

  /// <summary>
  /// Initializes a new instance of the <see cref="AdministrationApiController"/> class. 
  /// </summary>
  /// <param name="administrationService">
  /// The administration service.
  /// </param>
  public AdministrationApiController(IAdministrationService administrationService)
  {
    this.administrationService = administrationService;
  }
}
Posted on Friday, December 14, 2012 10:29 AM MVC , Unit Testing , Inversion Of Control (Ioc) | Back to top


Comments on this post: WebAPI Dependency Injection

No comments posted yet.
Your comment:
 (will show your gravatar)
 


Copyright © Aligned | Powered by: GeeksWithBlogs.net | Join free