ASP.NET Web API Dependency Injection

白昼怎懂夜的黑 提交于 2019-12-22 05:24:21

问题


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.


回答1:


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)
    {
        // ...
    }

    // ...
}


来源:https://stackoverflow.com/questions/44123323/asp-net-web-api-dependency-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!