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

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

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

IOC容器特性注入第六篇:利用MVC注入点,把容器启动
    #region MVC Inject
            System.Web.Mvc.DependencyResolver.SetResolver(new DaHua.Sites.DependencyResolve(DaHua.Common.Runtime.EngineContext.Current, System.Web.Mvc.DependencyResolver.Current));
            #endregion
IOC容器特性注入第六篇:利用MVC注入点,把容器启动

 

 实现化类:

IOC容器特性注入第六篇:利用MVC注入点,把容器启动
    /// <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

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

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

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

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

上一篇:分享在MVC3.0中使用jQuery DataTable 插件


下一篇:python3.9 manage.py runserver 报错问题解决