ASP.NET MVC 4和ASP.NET Web API中的Unity

Thought this will help someone who wants to learn Unity framework in ASP.NET MVC 4 and ASP.NET Web API. Since the controllers are called directly by the MVC framework and as soon as you start introduce Repository Pattern in your project , unity framework will be very handy create dependent objects in your MVC Controller or Web API Controller.  By Coding to Interfaces enables us to test the projects easily by any mocking frameworks.

认为这将对希望在ASP.NET MVC 4和ASP.NET Web API中学习Unity框架的人有所帮助。 由于控制器是由MVC框架直接调用的,并且一旦您开始在项目中引入存储库模式,统一框架将非常容易在MVC控制器或Web API控制器中创建依赖对象。 通过对接口进行编码,我们可以通过任何模拟框架轻松地测试项目。

Let us see how to use UNITY in MVC 4 Controllers.

让我们看看如何在MVC 4 Controller中使用UNITY。

There are 3 things should be followed while using Dependency Injection. Design, Register and Resolve.

使用依赖注入时应遵循3件事。 设计,注册和解决。

1. Design1.设计

Simplest of 3 steps I guess. Have the controller constructor takes a repository Interface like this.

我猜最简单的3个步骤。 让控制器构造函数采用这样的存储库接口。

public class TeamsController : Controller
    {
        private readonly ITeamRepository teamRepository;


        public TeamsController(ITeamRepository teamRepository)
        {
	this.teamRepository = teamRepository;
        }
....
} 
2. Register2.注册

How we are going to register the above dependency injection so that when the controller is called the unity jumps in creates the dependent objects.

我们将如何注册上述依赖项注入,以便在调用控制器时,Unity跳入会创建依赖项对象。

Registration can be done in two ways. Using the config.file and doing in the Code.

注册可以通过两种方式进行。 使用config.file并在代码中执行。

2.1 Let’s see how to register by web.config file.

2.1让我们看看如何通过web.config文件进行注册。

2.1.1. Place below secion inside(configuration -> configSections)

2.1.1。 放在secion下方(配置-> configSections)

<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />

<section name =“ unity” type =“ Microsoft.Practices。 统一配置 自负。 UnityConfi gurationSe 部分,Microsoft.Practices.Unity。 配置 离子“ />

2.1.2. Paste below <unity> element inside configuration section of web.cofig. Below I’m registering ITeamRepository so that whenever this object is passed in the constructor, unity framework will create concrete object which is in "mapto".We group these registration inside containers.

2.1.2。 粘贴在web.cofig的配置部分内的<unity>元素下方。 在下面,我注册ITeamRepository,以便每当在构造函数中传递此对象时,统一框架将在“ mapto”中创建具体的对象。我们将这些注册分组在容器内。

 <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias alias="Singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity"/>
    <alias alias="Transient" type="Microsoft.Practices.Unity.TransientLifetimeManager, Microsoft.Practices.Unity"/>

    <alias alias="ITeamRepository" type="PrecisionPrinting.OneFlow.WebAPI.Models.ITeamRepository, PrecisionPrinting.OneFlow.WebAPI" />
    <alias alias="TeamRepository" type="PrecisionPrinting.OneFlow.WebAPI.Models.TeamRepository, PrecisionPrinting.OneFlow.WebAPI" />
      <container>
        <register type="ITeamRepository" mapTo="TeamRepository" name="teamRepository" />
        <register type="PrecisionPrinting.OneFlow.WebAPI.Controllers.TeamsController, PrecisionPrinting.OneFlow.WebAPI">
            <lifetime type="Transient" />
              <constructor>
                <param name="teamRepository" >
                  <dependency type="TeamRepository"/>
                  </param>
              </constructor>
        </register>
      </container>
  </unity>

2.2. how to register in the code.

2.2。 如何在代码中注册。

//Create unitycontainer
IDependencyResolver ioc = new UnityDependencyResolver();
//Registration 
 ioc.Register<ITeamRepository>(new TeamRepository());
3. Resolve.3.解决。

Use the container to get the instances of the controller. Please see the attached controllerfactory file.

使用容器获取控制器的实例。 请参阅随附的controllerfactory文件。

Finally, we have to have below lines in your Application_Start method of global.asax.cs file. We can wrap below lines inside a static class.

最后,我们必须在global.asax.cs文件的Application_Start方法中包含以下几行。 我们可以将下面的行包装在静态类中。

//Mandatory line
IDependencyResolver ioc = new UnityDependencyResolver();
//below line is required if you don't use web.config file to register.
ioc.Register<ITeamRepository>(new TeamRepository());
below line should be added if you want Unity in WEB API controllers.
ControllerBuilder.Current.SetControllerFactory(new ControllerFactory(ioc));
//below line should be added if you want Unity in WEB API controllers.
 GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver();  

Some details of the attached files. Add the attached files to your solution.

附件的一些详细信息。 将附件添加到您的解决方案。

UnityDependencyResolver

UnityDependencyResolver

This class implements "IDependencyResolver"  which are required for MVC 4 controllers Dependency Injection. It also implements IDependencyScope, System.Web.Http.Dependencies.IDependencyResolver which are required for WEB API Dependency injection. Please remove the interfaces accordingly if you don't any of them.

此类实现MVC 4控制器依赖注入所必需的“ IDependencyResolver”。 它还实现了IDependencyScope,System.Web.Http.Dependenci es.IDepend encyResolv WEB API依赖关系注入所需的所有内容。 如果没有任何接口,请相应地删除它们。

Also in the method, " UnityDependencyResolver(IUnityContainer container)" comment last twp lines if you are registering in the code instead of web.config.

同样在方法中,“ UnityDependencyResolver(IU 康泰 ner容器)”如果您在代码中而不是web.config中注册,请在最后两行注释一下。

IDependencyResolver

IDependencyResolver

This is a custom class which can extended as required

这是一个自定义类,可以根据需要扩展

Let’s us see how to use Unity in WEB API Controllers.

让我们看看如何在WEB API控制器中使用Unity。

Here also we have to Design, Register api controller (either in web.config or in code) and Resolve. It is the same process as above except few more changes.

在这里,我们还必须设计,注册api控制器(在web.config或代码中)并解析。 除少量更改外,其余步骤与上述相同。

Resolve:

解决:

By Implementing IDependencyScope, System.Web.Http.Dependencies.IDependencyResolver in UnityDependencyResolver class

通过实现IDependencyScope,System.Web.Http.Dependenci es.IDepend encyResolv UnityDependencyResolver类中的er

we can use the same class to support both MVC 4 Controllers and We b API Controllers

我们可以使用相同的类来支持MVC 4控制器和We b API控制器

Tell the framework to use our Resolver for dependency injection by including the line below in application_start() event.

通过在application_start()事件中包含以下行,告诉框架使用我们的Resolver进行依赖项注入。

GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver();
ControllerFactory.cs ControllerFactory.cs IDependencyResolver.cs IDependencyResolver.cs UnityDependencyResolver.cs UnityDependencyResolver.cs

翻译自: https://www.experts-exchange.com/articles/11332/Unity-in-ASP-NET-MVC-4-and-ASP-NET-Web-API.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值