Search code examples
asp.net-mvcasp.net-web-apidependency-injectionautofacgeneric-handler

Register and resolve a class in generic handler using AutoFac


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.


Solution

  • 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 
    }