3

I have inherited this project, I normally do not unity as my dependency resolver, so forgive me if this is a dumb question.

I am getting he following message when I try and resolve a interface.

Inner Exception 1:

InvalidOperationException: No public constructor is available for type [ProjectName].ITest

Inner Exception 2:

InvalidRegistrationException: Exception of type 'Unity.Exceptions.InvalidRegistrationException' was thrown.

Now before anyone jumps on me and says I have no constructor the class looks like this... it has a constructor with no parameters.

namespace ProjectName
{
    public class Test : ITest
    {
        public Test()
        {
        }

        public int Foo() => 99;
    }

    public interface ITest
    {
        int Foo();
    }
}

So there is a constructor that has no parameters This is the class that is trying to resolve the class.

[Route("api/Test")]
public class TestController : ApiController
{

    [Dependency]
    public ITest Test { get; set; }


    public TestController()
    {

    }

    [HttpPost]
    public IHttpActionResult Post()
    {
        var i = Test.Foo();
        return Ok();
    }
}
Jackdaw
  • 7,626
  • 5
  • 15
  • 33
Ashley Kilgour
  • 1,110
  • 2
  • 15
  • 33
  • 1
    I'm guessing DI is set up wrong, `No public constructor is available for type [ProjectName].ITest` shounds like it is trying to instantiate an interface. – Jonesopolis Dec 18 '20 at 17:38

2 Answers2

5

The reason of exception:

InvalidOperationException: No public constructor is available for type [ProjectName].ITest

is because the DI is trying to create a instance of a interface ITest instead of Test.

You must register the dependency to resolve to Test when ask for ITest, something like:

services.AddTransient<ITest, Test>();
Leo
  • 1,990
  • 1
  • 13
  • 20
0

There is no call to the constructor either. There should be a [new] Test.Foo() there. Or make Foo() static.

krisam
  • 60
  • 5