locked
MEF Dependency injection to Self Hosted WebAPI v. 1 RRS feed

  • Question

  • User2006681893 posted

    Hi,

    I would like to use shared freamework in WEB API v1 which uses MEF for dependency injection in SelfHosted WEB API .

    For this I created  a class derived from IDependencyResolver & implemented the methods as shown below.

    public object GetService(Type serviceType)
            {
                var export = _container.GetExports(serviceType, null, null).SingleOrDefault();
                return null != export ? export.Value : null;
            }

    And set the dependency resolver as

    var config = new HttpSelfHostConfiguration("http://lonws21009:8080");
                    ControllerBuilder
                    config.DependencyResolver = new MefDependencyResolver(_container);

    When invoking the services, I am getting the below error.

    Controller does not have a default constructor

    Thursday, September 15, 2016 6:50 AM

All replies

  • User36583972 posted

    Hi pgupta95,

    Something in your code is trying to create new Your Controller(), but there is no constructor that accepts zero arguments. You need to properly enable and configure any dependency injection you are using.

    You may can define a default constructor (one with no params) for Your Controller.

    Also, I suggest you can use Dependency Injection in ASP.NET Web API 2.

    http://www.asp.net/web-api/overview/advanced/dependency-injection

    Best Regards,

    Yohann Lu

    Friday, September 16, 2016 4:38 AM
  • User2006681893 posted

    Thanks for your reply. I took reference of below URL only and set the MEF Dependency Resolver class object to HttpSelfHostConfiguration object.

    http://www.asp.net/web-api/overview/advanced/dependency-injection

    ar config = new HttpSelfHostConfiguration("http://lonws21009:8080");
                    ControllerBuilder
                    config.DependencyResolver = new MefDependencyResolver(_container);

    In my original message, you will find the code snippets. I am still getting the same error. 

    Controller does not have a default constructor

    Tuesday, November 29, 2016 10:54 AM