当前位置: 代码迷 >> ASP.NET >> 关于MVC3与Unity集成的一个困惑
  详细解决方案

关于MVC3与Unity集成的一个困惑

热度:5305   发布时间:2013-02-25 00:00:00.0
关于MVC3与Unity集成的一个疑惑
正在尝试使用Unity注入View,可是遇到了一点疑惑,如下:
在Application_Start中有如下代码:
C# code
var container = new UnityContainer();container.RegisterInstance<IMessageService>(new MessageService            {                Message = "You are welcome to our Web Camps Training Kit!",                            });            container.RegisterType<IViewPageActivator, IndexViewPageActivator>(new InjectionConstructor(container));            //注册类型并提供了构造函数所需的参数                        IDependencyResolver resolver = DependencyResolver.Current;            IDependencyResolver newResolver = new UnityDependencyResolver(container, resolver);            DependencyResolver.SetResolver(newResolver);

相应的IndexViewPageActivator类代码如下:
C# code
    public class IndexViewPageActivator : IViewPageActivator    {        IUnityContainer _container;        public IndexViewPageActivator(IUnityContainer container)        {            _container = container;        }        public object Create(ControllerContext controllerContext, Type type)        {            var o = _container.Resolve(type);            return o;        }    }

相应的UnityDependencyResolver类代码如下:
C# code
    public class UnityDependencyResolver : IDependencyResolver    {        IUnityContainer container;        IDependencyResolver resolver;        public UnityDependencyResolver(IUnityContainer container, IDependencyResolver resolver)        {            this.container = container;            this.resolver = resolver;        }        public object GetService(Type serviceType)        {            try            {                return this.container.Resolve(serviceType);            }            catch            {                return this.resolver.GetService(serviceType);            }        }        public IEnumerable<object> GetServices(Type serviceType)        {            try            {                return this.container.ResolveAll(serviceType);            }            catch            {                return this.resolver.GetServices(serviceType);            }        }    }

我不明白的是,在UnityDependencyResolver和IndexViewPageActivator中,相应的调用_container.Resolve都能返回实例,特别是在UnityDependencyResolver中,基本上不走return this.resolver.GetService(serviceType);这行代码,而我并没有操作过_container,难道MVC在某个地方向_container中注册过什么?或者是UnityContainer自己通过上下文自己注册或者进行了解析吗?

------解决方案--------------------------------------------------------
探讨

来个回复的吧,把分给了就结了
  相关解决方案