要使用 ASP.Net WebAPI 进行 DI,您需要为 DI 容器创建依赖关系解析器。
以下适用于 Ninject
public class NinjectDependencyResolver : System.Web.Http.Services.IDependencyResolver
{
private static IKernel m_Kernel;
public NinjectDependencyResolver()
{
m_Kernel = new StandardKernel();
}
public NinjectDependencyResolver(IKernel myKernel)
{
m_Kernel = myKernel;
}
public object GetService(Type serviceType)
{
return m_Kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return m_Kernel.GetAll(serviceType);
}
}
然后使用以下方法将其绑定到 Global.ascx 文件中:
GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new NinjectDependencyResolver(yourKernel));
这与 MVC3 依赖注入相似(但不完全相同)