2

I need some assistance. I am trying to use Autofac to get me a few dependencies that are need for a custom media formatter. I followed the Wiki but it is a little confusing. I am trying to use property injection for the media formatter since it needs to be registered with the global configuration.

Code:

public class UserMediaFormatter : JsonMediaTypeFormatter
{
    public UsersRepository repository { get; set; }
}

 public class WebApiApplication : System.Web.HttpApplication
 {
    GlobalConfiguration.Configuration.Formatters.Insert(2, new UserMediaFormatter());
    builder.RegisterType(typeof(UserMediaFormatter)).PropertiesAutowired()
               .As<MediaTypeFormatter>()
               .InstancePerApiControllerType(typeof (UsersController));

 }

 [AutofacControllerConfiguration]
 public class UsersController : ApiController
 {
 }
Jamie
  • 3,094
  • 1
  • 18
  • 28
  • 1
    Do you want to use your `UserMediaFormatter` globally in all of your controller? Because the `InstancePerApiControllerType` only registers it for the `UsersController` or this is what you would like to have anyway? – nemesv Sep 13 '13 at 04:53
  • That is what I would like to have happen, but for some reason it does not appear to be working. – Jamie Sep 13 '13 at 18:14

1 Answers1

1

If you want to let Autofac to add your custom formatter to the marked controllers then you don't need to add it to the GlobalConfiguration.Configuration.Formatters because it makes your formatter globally available and it prevents Autofac to inject properties on it.

So remove the GlobalConfiguration.Configuration.Formatters.Insert call

and use the following exact syntax to register your formatter:

builder.Register<MediaTypeFormatter>(c => new UserMediaFormatter())
       .PropertiesAutowired()
       .InstancePerApiControllerType(typeof(UsersController));
nemesv
  • 138,284
  • 16
  • 416
  • 359