日期:2014-05-17 浏览次数:20451 次
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);
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; } }
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); } } }