6

I would like to know if it is possible to do dependency injection (custom constructor) in a ASP.NET Web API without the use of third party libraries such as Unity or StructureMap and without Entity Framework.

What I would like to achieve is have a controller with a constructor such as:

public Controller(IDatabaseConnector connector) { ... }

I know for MVC you can make a custom ControllerFactory by inheriting from DefaultControllerFactory and then overriding the GetControllerInstance function. So I am sure there is an alternative for Web API.

4
  • Read up on IDependencyResolver for web api. Make sure it is for Web API as MVC has its own with the same name. Commented May 22, 2017 at 23:10
  • 1
    I ended up inheriting from IHttpControllerActivator and that did the trick for me. Commented May 22, 2017 at 23:23
  • When i was trying out asp core it had dependency injection in their sample page msdn.microsoft.com/en-us/magazine/mt703433.aspx Commented May 22, 2017 at 23:25
  • 1
    Dependency Injection doesn't require a DI Container at all. Hand-wiring your Dependency in the Composition Root is a common practice called Pure DI. As you already noticed, you need to implement a custom IHttpControllerActivator for this. Commented May 23, 2017 at 9:34

1 Answer 1

4

At first you should define your own IHttpControllerActivator:

public class CustomControllerActivator : IHttpControllerActivator
{
    public IHttpController Create(
        HttpRequestMessage request,
        HttpControllerDescriptor controllerDescriptor,
        Type controllerType)
    {
        // Your logic to return an IHttpController
        // You can use a DI Container or you custom logic
    }
}

Then you should replace the default activator in the Global.asax:

protected void Application_Start()
{
    // ...

    GlobalConfiguration.Configuration.Services.Replace(
        typeof(IHttpControllerActivator),
        new CustomControllerActivator());
}

Now you can use your rich Controller constructor:

public class UserController
{
    public UserController(
        IMapper mapper,
        ILogger logger,
        IUsersRepository usersRepository)
    {
        // ...
    }

    // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

I already did this as you could see in my comment on my post, but still thanks for the help! +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.