locked
Controller Injection on Webapi: SomeController<T> ... not possible? RRS feed

  • Question

  • User-271049563 posted

    Greetings,

    I'm injecting WebApi manually (no Containers) using the ControllerActivator(ControllerFactory on MVC). This injection works nicely with MVC and works with Web Api up to the Controller injection.

    The idea is to tell each controller of the same application to fetch the data from repositories of possibly different types(I.E. database, webapi, List, etc).

    There is seems to be a limitation here (or I'm missing something). Hopefully somebody can clarify.

    //MyClassController.cs
    
    public class MyClassController<T> : ApiController
    {
      private readonly GenericRepository<T, MyClass> myClassRepository;
    
      public MyClassController(GenericRepository<T, MyClass> myClassInterface)
      {
          this.myClassRepository = myClassInterface;
      }
    
      // more code...
    }
    
    
    //ControllerActivator.cs
    
    
    public class ControllerActivator : IHttpControllerActivator
    {
        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor,
            Type controllerType)
        {
            if (controllerType.Name.ToLower().Contains("myclasscontroller"))
            {
                var p = new MyClass
                {
                    a=1,
    		b=2,
    		c=3
                };
                var myClasses = new List<MyClass> { p };
                var repository = new GenericRepository<List<MyClass>, MyClass>(myClasses);
    
                // WebApi limitation???: Doesn't work with Controller Injection
                var controller = new MyClassController<List<MyClass>>(repository);
    
                return controller;
            }
    
    	return null;
        }
    }
    
    //Global.asax.cs
    
    protected void Application_Start()
        {
    	// some code
      	GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new ControllerActivator());
        }
    }

    Thanks,

    Marcelo

     

     

    Tuesday, March 18, 2014 10:23 AM

Answers

  • User1066278571 posted

    For web API just implement the IDependencyResolver interface and add it to your config

    config.DependencyResolver = new YourDependencyResolver();

    Then construction injection will be used with your Resolver.

    greetings Damien

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 24, 2014 8:44 AM

All replies