如何在同一个ASP.Net MVC项目中使用Unity MVC和Unity WebAPI

Sou*_*ouk 1 asp.net-mvc unity-container bootstrapper asp.net-web-api2

我正在尝试将WebAPI添加到现有的ASP.Net MVC项目中,我的问题是关于Unity:

在单独使用UnityMVC之前,该项目在App_Start文件夹中具有UnityConfig类,其代码如下:

container.RegisterType<IUnitOfWork, UnitOfWork>(new PerRequestLifetimeManager());
container.RegisterType<IDataContext, tfe_schemaContext>(new PerRequestLifetimeManager());

container.RegisterType<IPrintJobService, PrintJobService>(new PerRequestLifetimeManager());
container.RegisterType<IRepository<print_job>, Repository<print_job>>(new PerRequestLifetimeManager());
Run Code Online (Sandbox Code Playgroud)

为了使用WebAPI,我通过NuGet添加了UnityWebAPI,这个动作在App_Start文件夹中添加了UnityMvcActivator类.

执行项目时显示以下错误:"类型Unity.WebApi.UnityDependencyResolver似乎未实现Microsoft.Practices.ServiceLocation.IServiceLocator.参数名称:commonServiceLocator".

我使用Bootstrapper类找到了不同的代码示例,但没有使用UnityConfig类或UnityMvcActivator.

在Bootrstrapper类中,类型的注册是这样的:

container.RegisterType<IProductServices, ProductServices>().RegisterType<UnitOfWork>(new HierarchicalLifetimeManager());
Run Code Online (Sandbox Code Playgroud)

我对这一切有点失落,请帮助我理解并修复此错误.

Sam*_*ari 6

您似乎使用了错误或过时的NuGet包.请尝试使用Unity的官方软件包.因此,删除与Unity相关的所有包,并在Package Manager控制台中添加以下包:

Install-Package Unity.Mvc
Install-Package Unity.AspNet.WebApi
Run Code Online (Sandbox Code Playgroud)

现在,您的项目中有一个Unity容器,可以很好地与MVC和WebAPI配合使用.