码迷,mamicode.com
首页 > Web开发 > 详细

IOC容器特性注入第六篇:利用MVC注入点,把容器启动

时间:2014-06-12 08:32:12      阅读:367      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

这里是利用MVC三个注入点中的:IDependencyResolver 进行注入

在全局类中Global.asax代码如下:

bubuko.com,布布扣
    #region MVC Inject
            System.Web.Mvc.DependencyResolver.SetResolver(new DaHua.Sites.DependencyResolve(DaHua.Common.Runtime.EngineContext.Current, System.Web.Mvc.DependencyResolver.Current));
            #endregion
bubuko.com,布布扣

 

 实现化类:

bubuko.com,布布扣
    /// <summary>
    /// MVC注入点
    /// </summary>
    public class DependencyResolve:IDependencyResolver {

        #region Fields
        private IEngine _engine; //容器引擎
        private IDependencyResolver _innerResolver; //内部依赖解析接口
        #endregion
        #region .ctor

        public DependencyResolve(IEngine engine, IDependencyResolver innerResolver)
        {
            this._engine = engine;
            this._innerResolver = innerResolver;
        }
        #endregion

        #region Methods
        public object GetService(Type serviceType)
        {
            var service = _engine.TryResolve(serviceType);
            if (service == null) {
                service = _innerResolver.GetService(serviceType);
            }
            return service;
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            var services = _engine.ResolveAll(serviceType);
            if (services == null)
            {
                services = _innerResolver.GetServices(serviceType);
            }
            return services;
        }
        #endregion

    }
bubuko.com,布布扣

好了,到此为主,整个过程注入完毕,可以在控制器(Controller)的构造函数进行获取服务也可以利用TryResolve 获取服务。

IOC容器特性注入第六篇:利用MVC注入点,把容器启动,布布扣,bubuko.com

IOC容器特性注入第六篇:利用MVC注入点,把容器启动

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/flyfish2012/p/3782622.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!