Search code examples
c#unity-container

Exception is: InvalidOperationException - The current type, log4net.ILog, is an interface and cannot be constructed. Are you missing a type mapping?


I am using unity-container.I have register my class to IOC container. When i am trying to create instance of Auth class, I am getting following exception: Exception is: InvalidOperationException - The current type, log4net.ILog, is an interface and cannot be constructed. Are you missing a type mapping?

Please let me know if i am doing something wrong?

My code:

    using Unity;
    Public Main()
    {
     private readonly IUnityContainer container;
     public override void Instantiate()
     {
       container.RegisterSingleton<IAuthentication, Auth>("Auth");
     }

     public Authenticate()
     {
       var instance = container.Resolve<IAuthentication>("Auth");**//Getting exception here**
     }
    }

Auth class:

    public class Auth: IAuthentication
    {
      private readonly ILog log;
      private IImpID impIDobj;
      public Auth(ILog log, IImpID impIDobj)
        {
            this.impIDobj= impIDobj;
            this.log = log;
        }

        public Auth()
            : this(LogManager.GetLogger("Auth"), new CAuth())
        {
        }
        public Authenticate()
        {
          impIDobj.Authenticate(data);
         //Some logics
        }
    }

Solution

  • Thanks all of you for feedback. But i am able to solve this issue with "InjectionConstructor". More info is here.

    My new Auth class:

     public class Auth: IAuthentication
    {
      private readonly ILog log;
      private IImpID impIDobj;
      public Auth(ILog log, IImpID impIDobj)
        {
            this.impIDobj= impIDobj;
            this.log = log;
        }
    
        [InjectionConstructor]
        public Auth()
            : this(LogManager.GetLogger("Auth"), new CAuth())
        {
        }
        public Authenticate()
        {
          impIDobj.Authenticate(data);
         //Some logics
        }
    }