简体   繁体   English

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

[英]How to use Unity MVC & Unity WebAPI in the same ASP.Net MVC project

I'm trying to add a WebAPI to an existing ASP.Net MVC project and my question is regarding Unity: 我试图将WebAPI添加到现有的ASP.Net MVC项目中,而我的问题是关于Unity的:

Before with UnityMVC alone, the project had in the App_Start folder, the class UnityConfig with the following code: 在单独使用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());

To use a WebAPI, I added UnityWebAPI via NuGet and this action added UnityMvcActivator class in the App_Start folder. 要使用WebAPI,我通过NuGet添加了UnityWebAPI,并且此操作在App_Start文件夹中添加了UnityMvcActivator类。

The following error displayed when I execute the project: "The type Unity.WebApi.UnityDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator. Parameter name: commonServiceLocator". 执行项目时显示以下错误:“类型Unity.WebApi.UnityDependencyResolver似乎未实现Microsoft.Practices.ServiceLocation.IServiceLocator。参数名称:commonServiceLocator”。

I found different examples of code using a Bootstrapper class but without using the UnityConfig class or UnityMvcActivator. 我发现了使用Bootstrapper类而不使用UnityConfig类或UnityMvcActivator的不同代码示例。

In the Bootrstrapper class, the registration of the types is like this: 在Bootrstrapper类中,类型的注册如下:

container.RegisterType<IProductServices, ProductServices>().RegisterType<UnitOfWork>(new HierarchicalLifetimeManager());

I'm a little bit lost with all this, please help me understand and fix this error. 我对这一切有点迷失,请帮助我理解并解决此错误。

It seems you are using wrong or outdated NuGet packages. 看来您使用的是错误或过时的NuGet软件包。 Try use Unity's official packages instead. 尝试改用Unity的官方软件包。 Therefore remove any packages related to Unity and add following packages in Package Manager Console: 因此,请删除与Unity相关的所有程序包,并在程序包管理器控制台中添加以下程序包:

Install-Package Unity.Mvc
Install-Package Unity.AspNet.WebApi

Now you have one Unity container in your project which works well with MVC and WebAPI. 现在,您的项目中有一个Unity容器,可与MVC和WebAPI很好地配合使用。

You can also try by separating the projects. 您也可以尝试分离项目。

One project four you MVC code and another project for your WebAPI code. 一个项目是四个MVC代码,另一个项目是WebAPI代码。 That way you will install Unity.MVC in your MVC project and Unity.WebAPI in your WebAPI project. 这样,您将在MVC项目中安装Unity.MVC,并在WebAPI项目中安装Unity.WebAPI。

After that, you can consume the services from your MVC Application without any problem. 之后,您可以毫无问题地使用MVC应用程序中的服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM