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

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

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

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

 

 实现化类:

    /// <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

    }

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

下一篇:

IOC容器特性注入第七篇:请求上下文作用域

posted on 2014-06-11 19:44  ~紫鱼~  阅读(1029)  评论(0编辑  收藏  举报