Unity.WebApi | Make sure that the controller has a parameterless public constructor

前端 未结 6 515
独厮守ぢ
独厮守ぢ 2020-12-19 10:48

I am using the Unity.WebApi NuGet package (Unity 4.0.1 and Unity.WebApi 5.2.3) in an ASP.NET WebApi solution. The issue I am facing is that when attempting to run the code,

6条回答
  •  忘掉有多难
    2020-12-19 11:36

    I'm using Unity of version 4.0.1 and in my case the nested dependency Repository have had two public constructors and Unity hasn't managed to choose the parameterless constructor.

    Thus, I've just specified the other one as protected to quickly solve the issue.

        public Repository() : this( ... ) { ... }
    
        // if need to make public, make sure that the dependency injection container
        // will choose the parameterless constructor;
        // Unity has had issues with that by default
        protected Repository(DbContext context) : base() { ... }
    

    IMO, Unity could have managed to find the "possible to call" constructor - as it had no DbContext (or any derived context) registered.

    Please note that by default Unity chooses a constructor with the maximum number of arguments.

    So yes, it's also possible to decorate the proper constructor with InjectionConstructorAttribute as it's described here and here - but I even don't have a Unity reference in my data access layer (and don't want to).

    Please tell me if such behavior has changed in the later versions.

提交回复
热议问题