1

I have a class called Config in my WebAPI project which has one constructor injection of a service.

 public class Config: IConfig
 {
     protected readonly IConfigService _configService;
     public Config(IConfigService configService)
     {
         this._configService = configService;
     }
}

I need to use this Config class in a generic handler used for image upload. Can anyone help me to register this Config class in the Startup class and resolve it in Handler class. I did try it in normal way, but getting no parameterless constructor found error.

Cyril Durand
  • 15,834
  • 5
  • 54
  • 62
Dileep Paul
  • 167
  • 3
  • 17

1 Answers1

3

Due to ASP.net internal design restriction, the is no way to use constructor injection with generic handler.

In your startup class, ensure that the DependencyResolver is defined :

// Set the dependency resolver to be Autofac.
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

Then in the constructor of your HttpHandler use the DependencyResolver class :

public class TestHandler : IHttpHandler 
{
    public TestHandler()
    {
        this._config = DependencyResolver.Current.GetService(typeof(IConfig)); 
    }

    private readonly IConfig _config; 

    // implements IHttpHandler 
}
Cyril Durand
  • 15,834
  • 5
  • 54
  • 62