使用 MVC5 和 WebApi2 控制器进行适当的依赖注入的常见连接点是什么?
What is the common hook up point for a proper Dependency Injection with MVC5 and WebApi2 controllers?
我在同一个项目中同时拥有 MVC 控制器和 WebApi 控制器。我想通过它们的构造函数将服务和记录器注入控制器。 DependencyResolver
是适当的扩展点吗?我可以通过 MVC 控制器和 WebApi 控制器共享相同的服务和记录器吗?我使用 Unity 作为我的 IoC 容器。
WebAPI和MVC是完全独立的框架。它们每个都支持 DI,并且它们被设计为在同一个项目中工作,前提是您在 composition root.[=18 中同时实现 System.Web.Mvc.IDependencyResolver
(或 System.Web.Mvc.IControllerFactory
)和 System.Web.Http.IDependencyResolver
=]
一般来说,大多数主要的 DI 容器都有 NuGet 包,可以使集成变得容易一些,但您必须查阅有关您使用的容器的文档。
Here is an article 详细介绍了如何集成 Unity。安装 Unity.WebApi
和 Unity.Mvc5
包并按如下方式添加配置。
using Microsoft.Practices.Unity;
using System.Web.Http;
using System.Web.Mvc;
namespace WebApplication1
{
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
DependencyResolver.SetResolver(new Unity.Mvc5.UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
}
}
}
我在同一个项目中同时拥有 MVC 控制器和 WebApi 控制器。我想通过它们的构造函数将服务和记录器注入控制器。 DependencyResolver
是适当的扩展点吗?我可以通过 MVC 控制器和 WebApi 控制器共享相同的服务和记录器吗?我使用 Unity 作为我的 IoC 容器。
WebAPI和MVC是完全独立的框架。它们每个都支持 DI,并且它们被设计为在同一个项目中工作,前提是您在 composition root.[=18 中同时实现 System.Web.Mvc.IDependencyResolver
(或 System.Web.Mvc.IControllerFactory
)和 System.Web.Http.IDependencyResolver
=]
一般来说,大多数主要的 DI 容器都有 NuGet 包,可以使集成变得容易一些,但您必须查阅有关您使用的容器的文档。
Here is an article 详细介绍了如何集成 Unity。安装 Unity.WebApi
和 Unity.Mvc5
包并按如下方式添加配置。
using Microsoft.Practices.Unity;
using System.Web.Http;
using System.Web.Mvc;
namespace WebApplication1
{
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
DependencyResolver.SetResolver(new Unity.Mvc5.UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
}
}
}