ASP.NET Web API依赖注入 [英] ASP.NET Web API Dependency Injection
问题描述
我想知道在不使用第三方库(例如Unity或StructureMap)且没有实体框架的情况下,是否可以在ASP.NET Web API中进行依赖项注入(自定义构造函数)。
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) { ... }
我知道MVC可以通过以下方式创建自定义ControllerFactory从DefaultControllerFactory继承,然后重写GetControllerInstance函数。因此,我确定还有Web API的替代方法。
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.
推荐答案
首先,您应该定义自己的 IHttpControllerActivator
:
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
}
}
然后应替换默认值 Global.asax
中的激活器:
Then you should replace the default activator in the Global.asax
:
protected void Application_Start()
{
// ...
GlobalConfiguration.Configuration.Services.Replace(
typeof(IHttpControllerActivator),
new CustomControllerActivator());
}
现在,您可以使用功能丰富的 Controller
构造函数:
Now you can use your rich Controller
constructor:
public class UserController
{
public UserController(
IMapper mapper,
ILogger logger,
IUsersRepository usersRepository)
{
// ...
}
// ...
}
这篇关于ASP.NET Web API依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!