Ashley Kilgour
Ashley Kilgour

Reputation: 1258

No public constructor is available Unity.Exceptions.InvalidRegistrationException

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();
    }
}

Upvotes: 3

Views: 12482

Answers (2)

krisam
krisam

Reputation: 60

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

Upvotes: 0

Leo
Leo

Reputation: 2360

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>();

Upvotes: 7

Related Questions