返回首页
当前位置: 主页 > 网络编程 > .Net实例教程 >

Unity框架在asp.net Web Api中的应用实例教程

时间:2016-10-09 21:46来源:2018年最新注册送彩金www.zhixing123.cn 编辑:麦田守望者

 Unity是微软Enterprise Library中的一个组件,这个组件提供了一个简单的方法来实现依赖注入模式,从而解耦各对象间的依赖关系。本文将介绍如何将Unity框架与Asp.net Web Api进行结合使用。

一、建立Asp.net Web Api项目



二、安装Unity


三、创建三个类和一个配置文件:


1、BaseHttpApplication类的基类是HttpApplication,在其静态构造函数中实现Unity的相关配置,包括读取unity.config文件内容并配置UnityContainer,设置全局配置中的DependencyResolver,以及设置当前的ControllerFactory(MVC普通Controller中用到),详细代码如下:
         public class BaseHttpApplication : HttpApplication
    {
        static IUnityContainer container = new UnityContainer();
 
        static BaseHttpApplication()
        {
 
            var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = HttpContext.Current.Server.MapPath("~/unity.config") };
            System.Configuration.Configuration configuration =
                ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            var unitySection = (UnityConfigurationSection)configuration.GetSection("unity");
            container.LoadConfiguration(unitySection);
 
            UnityResolver resolver = new UnityResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
 
            UnityControllerFactory factory =
new UnityControllerFactory(container);
            ControllerBuilder.Current.SetControllerFactory(factory);
        }
}
 

2、Unity.config是一个配置文件,格式为xml,存储Unity的配置信息,基本内容如下:

         其中的Register节点定义接口与实现类的对应关系,在实际项目主要是添加与维护Register节点内容。

3、UnityControllerFactory类实现MVC普通Controller的Unity注入(默认的DefaultControllerFactory不能实现Controller的依赖注入),详细代码如下:
public class UnityControllerFactory : DefaultControllerFactory, IControllerActivator
    {
        private readonly IUnityContainer container;
 
        public UnityControllerFactory(IUnityContainer container)
        {
            this.container = container;
        }
 
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            return container.Resolve(controllerType) as IController;
        }
 
        public IController Create(RequestContext requestContext, Type controllerType)
        {
            return container.Resolve(controllerType) as IController;
        }
}
 

4、UnityResolver类实现ApiController的依赖注入,实现了IDependencyResolver接口,详细代码如下:
 
public class UnityResolver : IDependencyResolver
    {
        protected IUnityContainer container;
 
        public UnityResolver(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            this.container = container;
        }
 
        public object GetService(Type serviceType)
        {
            try
            {
                return container.Resolve(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return null;
            }
        }
 
        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return container.ResolveAll(serviceType);
            }
            catch (ResolutionFailedException)
            {
                return new List<object>();
            }
        }
 
        public IDependencyScope BeginScope()
        {
            var child = container.CreateChildContainer();
            return new UnityResolver(child);
        }
 
        public void Dispose()
        {
            container.Dispose();
        }
}
 
四、在Controller中的应用注入:

Controller的注入一般采用构造函数注入的,在unity.config进行类型注册后,即可实现具体的依赖注入,以下给出普通Controller及ApiController的构造函数注入示例:

1、MVC普通Controller的注入:
public class AccountController : Controller
    {
        IRoleService _roleService;
        IUserService _userService;
        public AccountController(IRoleService roleService, IUserService userService)
        {
            _roleService = roleService;
            _userService = userService;
        }
 
        [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
}
}

2.   ApiController的注入:
    public class AccountController : ApiController
    {
        IAccountService _accountService;
        IUserService _userService;
        ILogService _logService;
        public AccountController(IAccountService pAccuntService, IUserService userService, ILogService logService)
        {
            _accountService = pAccuntService;
            _userService = userService;
            _logService = logService;
    }
}
 
【结束语】
         本文简单介绍了如何在asp.net MVC中使用unity实现依赖注入,以完整代码展示了普通Controller和ApiController的依赖注入,并且考虑到实际项目中必然存在大量的注入匹配关系,将Unity的配置独立存储于unity.config配置文件中,便于开发人员的编辑与维护。
顶一下
(0)
0%
踩一下
(0)
0%
标签(Tag):Unity框架
------分隔线----------------------------
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
验证码:点击我更换图片
博聚网