Unable to resolve service type while injecting dependencies

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

When implementing .NET Core dependency injection inside of ASP.NET Core or .NET Core. Assume you have implemented some class like 'IoTService.Config.GatewayConfig' and get following error on startup:

{"message":"Unable to resolve service for type 'IoTService.Config.GatewayConfig' while attempting to activate 'IoTService.GatewayHelper'.","type":"InvalidOperationException"}

This is how I have initialized injection:

services.Configure<GatewayConfig>(Configuration.GetSection("IotHubMap"));
services.AddScoped<IGatewayHelper, GatewayHelper>();

The error shown above will be thrown if the constructor shown in yellow is not implemented. Internal implementation is always looking for IOptions. The code shown below demonstrate hot to workaround this error and how to implement injectable class out of ASP.NET and need to implement IOptions interface.

public class GatewayHelper : ISOmething
    {
         private GatewayConfig m_Cfg;

       public GatewayHelper(IOptions<GatewayConfig> options) : this(options.Value)
        {

        }

       
        public GatewayHelper(GatewayConfig cfg)
         {
            this.m_Cfg = cfg;
        }


Posted Aug 15 2017, 05:23 PM by Damir Dobric
Filed under: ,
developers.de is a .Net Community Blog powered by daenet GmbH.