1

I have followed the below sample and it works fine until I have replaced the ProductsContext class by my own LDAPConnector class that need to get data from AD and since it's not working and get the Parameterless error.

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

What I should add in the webAPIConfig.cs in order to register this new class ?

I have try this but it's not working:

container.RegisterType<ILDAPConnector, LDAPConnector>(new HierarchicalLifetimeManager());

I have also tried to add parameterless construction in both Controller and in the LDAPConnector class but still get the same issue.

The controller

    public class ADAccountController : ApiController
{
    IADAccountRepository _repository;

    public ADAccountController() : base()
    {
    }

    public ADAccountController(IADAccountRepository repository)
    {            
        _repository = repository;            
    }

    public IHttpActionResult GetByID(string id)
    {
        try
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                AccountAD contact = _repository.GetByID(id);

                if (contact == null)
                {
                    return NotFound();
                }
                return Ok(contact);

the Repository where I get the error on the LDAPConnector connector = new LDAPConnector();

public class ADAccountRepository : IADAccountRepository
{
    static ConcurrentDictionary<string, AccountAD> _todos = new ConcurrentDictionary<string, AccountAD>();

    private LDAPConnector connector = new LDAPConnector();

    public ADAccountRepository()
    {            
        Add(new AccountAD { Name = "Item1" });
    }       

    public AccountAD GetByID(string id)
    {
        return connector.GetAccountDetails(id);

        //AccountAD item;
        //_todos.TryGetValue(id, out item);
        //return item;
    }

The ADConnector

   public class LDAPConnector : ILDAPConnector
{        

    public LDAPConnector ()
    { 

    }

    public AccountAD GetAccountDetails(string id)
    {
        AccountAD _AccountDetails = new AccountAD();

        List<SearchResult> searchResult = new List<SearchResult>();

finally the webapiconfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var container = new UnityContainer();
        container.RegisterType<IADAccountRepository, ADAccountRepository>(new HierarchicalLifetimeManager());
        container.RegisterType<ILDAPConnector, LDAPConnector>(new HierarchicalLifetimeManager());
        //container.RegisterType<LDAPConnector>(new InjectionFactory(c => new LDAPConnector()));
        config.DependencyResolver = new UnityResolver(container);            

        // Web API routes
        config.MapHttpAttributeRoutes();

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

        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    }
}

error reported:

{"Message":"An error has occurred.","ExceptionMessage":"An error occurred when trying to create a controller of type 'ADAccountController'. 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 'ADConnector.Controllers.ADAccountController' 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)"}}
Denfer06
  • 25
  • 5
  • Looks like a dupe of [this question](http://stackoverflow.com/questions/24254189/make-sure-that-the-controller-has-a-parameterless-public-constructor-error). Can you check if that helps you out? – Andrei Mar 01 '16 at 10:18
  • Could you update your question with the exact error you're seeing, please? It'd help us get a better understanding of what's going wrong. – Joseph Woodward Mar 01 '16 at 10:18
  • I have already checked the solution from Andrei but still get the issue. – Denfer06 Mar 01 '16 at 13:49

1 Answers1

0

Unity tries to pick the constructor with the most arguments, I think in this case the exception is misleading.

Not got IDE to hand, but does this work?

container.RegisterType<ILDAPConnector>(new HierarchicalLifetimeManager(),
    new InjectionFactory(c => new LDAPConnector())); 
sambomartin
  • 6,663
  • 7
  • 40
  • 64
  • I get the error 'Microsoft.Practices.Unity.UnityContainer' does not contain a definition for 'Register' when I try to add your code – Denfer06 Mar 01 '16 at 11:11
  • `RegisterType` - apologies – sambomartin Mar 01 '16 at 11:12
  • get the same error (I have update the question content with it) – Denfer06 Mar 01 '16 at 11:14
  • now it failed on the "new LDAPConnector()" from the Container Register and report in the inner exception: Object reference not set to an instance of an object – Denfer06 Mar 01 '16 at 13:50
  • I have adapted the sample get from MS (above link) and it works fine without the need to register new Type in the container. I have something in my solution that generate the error but cannot figure what. I will start my solution from scratch and see when it crached. – Denfer06 Mar 01 '16 at 15:37
  • @Denfer06 i will check back later when at computer, hope you fix it before then :) – sambomartin Mar 01 '16 at 15:46
  • I finally found the issue that was from some Static member that was not existing. I was getting some appsetting from config file and one was not existing. So Controller was not able to instanciate the class due to this. Thanks for your help – Denfer06 Mar 04 '16 at 08:20