Dependency injection into Models on a Web Api action?

90 views
Skip to first unread message

mark.cl...@gmail.com

unread,
Jul 18, 2015, 12:11:41 AM7/18/15
to aut...@googlegroups.com
I'm looking for advice on injecting dependencies into models on a Web Api 2.2 controller action. To be clear here's an example that captures what I want to do:

public class WidgetController : ApiController
{
public IHttpActionResult Post(Widget widget) {
// ... assert that model state is valid (easy)
// ... do some persistence stuff (easy)
// ... return a success message (easy)
}
}

public class Widget : IValidatableObject
{
[Required]
public string WidgetName {get;set;}

private IWidgetRepository widgetRepository;

// **Help!** How do I make autofac inject this dependency?
public Widget(IWidgetRepository widgetRepository) {
this.widgetRepository = widgetRepository;
}

public IEnumerable<ValidationResult> Validate(ValidationContext ctx) {
if(!this.widgetRepository.IsWidgetNameAvailable(Name)) {
yield return new ValidationResult(...)
}
}
}


Now, when the WidgetController.Post method is invoked, it will new up a Widget but the widgetRepository dependency is set to null, and the call stack looks a bit like this (heavily truncated):

Example.dll!Example.Models.Widget.Widget(Example.Services.IWidgetRepository widgetRepository) Line 9
Newtonsoft.Json.dll!Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObjectUsingCreatorWithParameters(Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty containerProperty, Newtonsoft.Json.Serialization.ObjectConstructor<object> creator, string id) Unknown


Traditionally if I were building an MVC project I would set up model dependency injection by setting ModelBinders.Binders.DefaultBinder to a custom binder whose CreateModel method would invoke DependencyResolver.Current.GetService, but there seems to be no parallel to this in Web Api 2.2.

I am not sure where to proceed from here. I have looked into creating a MediaTypeFormatter which captures all application/json requests and doing the dependency injection there, but I'm not sure if this is idiomatic or even correct. I would appreciate any advice as to how I can inject dependencies into models with Autofac and Web Api 2.2.

mark.cl...@gmail.com

unread,
Jul 18, 2015, 2:30:26 AM7/18/15
to aut...@googlegroups.com
I was able to answer my own question by reading these Json.NET release notes. Specifically the AutofacContractResolver section.
Reply all
Reply to author
Forward
0 new messages