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

2

3

I am struggling with this problem of dependency injection using untiy. I have implemented according to this link https://www.asp.net/web-api/overview/advanced/dependency-injection

But got this error:

{
  "Message": "An error has occurred.",
  "ExceptionMessage": "An error occurred when trying to create a controller of type 'WebAPIController'. Make sure that the controller has a parameterless public constructor.",
  "ExceptionType": "System.InvalidOperationException",
  "StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
  "InnerException": {
    "Message": "An error has occurred.",
    "ExceptionMessage": "Type 'Fairmoves.Controllers.WebAPIController' does not have a default constructor",
    "ExceptionType": "System.ArgumentException",
    "StackTrace": "   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
  }
}

My Web Api Controller:

[RoutePrefix("api/WebAPI")]
public class WebAPIController : ApiController
{
    private readonly IUserBusinessService UserBusinessService;
    private readonly ILoginBusinessService LoginBusinessService;

    //public WebAPIController():base()
    //{
    //}

    public WebAPIController(IUserBusinessService UserBusinessService, ILoginBusinessService LoginBusinessService)
    {
        this.UserBusinessService = UserBusinessService;
        this.LoginBusinessService = LoginBusinessService;
    }
    [HttpPost]
    public IHttpActionResult Login([FromBody]AuthModels.LoginModel model)
    {
        // string strUserId = credentials.LoginName;
        //string strPassword = credentials.Password;
        var serviceResultDAO1 =  LoginBusinessService.LoginUserSubmit(model.LoginName);
    }
}

UnityResolver.cs:

public class UnityResolver:IDependencyResolver
{
    protected IUnityContainer container;

    public UnityResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }
        this.container = container;
    }

    [DebuggerStepThrough]
    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    [DebuggerStepThrough]
    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public void Dispose()
    {
        container.Dispose();
    }

}

}

WebApiConfig.cs:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        //config.DependencyResolver = new NinjectResolver();

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

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Unable to identify where the problem is? Can please get into the code and let me know. I have followed all these below links

Make sure that the controller has a parameterless public constructor?

Autofac - Make sure that the controller has a parameterless public constructor

Make sure that the controller has a parameterless public constructor using Ninject

Make sure that the controller has a parameterless public constructor error

But none of these solved my problem.

Otic answered 6/1, 2017 at 5:45 Comment(13)
The problem seems that application is not able to resolve the dependency for the constructor parameters, can you please check that .dll of the implemented class is present in the bin folder of the web API?Chaddie
Yes, that's the problem.Otic
Please check this asp.net/web-api/overview/advanced/dependency-injection and check with your code if you missing somethingChaddie
Nothing i missed. I checked thrice.Otic
Try registering at Application_Start and use GlobalConfiguration.Configuration.DependencyResolver = resolver;Chaddie
Let us continue this discussion in chat.Chaddie
take a look at this answer it might be helpfulSpotweld
Have you registered your controllers? You need to make sure Unity can 'see' your controllers and perform the necessary injection.Executory
Yes, registered @PhilCooperOtic
sorry .. are you sure are you bootstrapping the unity?Makowski
do you have a file called UnityWebApiActivator maybe?Makowski
No, I dont't have that file.Otic
Thank you for the link @Spotweld . But i didn't have any configuration setup in Startup.cs file as produced in the answer of that link.Otic
O
9

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!

Otic answered 10/1, 2017 at 13:11 Comment(1)
Unity.WebAPI Nuget component solved my problem.. ThanksUmbel
N
2

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.

Notus answered 12/9, 2018 at 7:42 Comment(1)
An alternative way...ok @NotusOtic

© 2022 - 2024 — McMap. All rights reserved.