Make sure that the controller has a parameterless public constructor in web api?

只愿长相守 提交于 2019-12-06 16:07:27

As i am using both MVC and WebAPI in one project, i understood by using this link that i need to resolve both dependencies.

So, i removed below code in WebAPIConfig.cs file

var container = new UnityContainer();
    container.RegisterType<ILoginBusinessService, LoginBusinessService>(new HierarchicalLifetimeManager());
    container.RegisterType<IUserBusinessService, UserBusinessService>(new HierarchicalLifetimeManager());
    config.DependencyResolver = new UnityResolver(container);

After i installed one package called Unity.WebAPI in my project.

Added below code in UnityConfig.cs file

GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);

That's it, solved my problem!

I guess you were merging WebAPI into MVC which was tightly coupled, that now decoupling by adding a Dependency injection hence I am doing same as @Edukondalu thaviti said above, in addition to that changing little code that worked for me perfectly.

  1. Install Unity.WebAPI and Unity.WebApi.5.1 using Manage Nuget Packages

    Note:After completion of installation dialog box will open and ask you to overwrite Unity.Config.cs file, simply select No

  2. Make sure to exist UnityConfig.RegisterComponents(); inside Application_Start() method at Global.asax.cs file

  3. Now include

    container.RegisterType<IWebAPIBusinessService, WebAPIBusinessService>(); container.RegisterType<IWebAPIDomainService, WebAPIDomainService>(); container.RegisterType<IWebAPIDataService, WebAPIDataService>(); GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container); inside the method RegisterComponents() at Unity.Config.cs file. Assuming that you were already created instance for current class.

Now run your project. The above code worked for me perfectly, If you cross over any mistakes please correct me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!