MVC TIP8:为控制器增加有参构造函数(为了注入等其它用途)
控制器本身是不带有参的构造函数的,如果我们为控制器仅仅提供有参的构造函数,就会报错。不过,可以利用DependencyResolver的SetResolver方法,让ASP.NET MVC支持有参的构造函数。
1:为系统准备两个类型,如下:
注意,这里要实现的是让控制器支持Unity注入。
UnityControllerFactory代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class UnityControllerFactory : DefaultControllerFactory { IUnityContainer container; public UnityControllerFactory(IUnityContainer container) { this .container = container; } protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType) { if (controllerType == null ) { return null ; } return container.Resolve(controllerType) as IController; } } |
UnityDependencyResolver代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class UnityDependencyResolver : IDependencyResolver { IUnityContainer container; public UnityDependencyResolver(IUnityContainer container) { this .container = container; } public object GetService(Type serviceType) { if (! this .container.IsRegistered(serviceType)) { return null ; } return container.Resolve(serviceType); } public IEnumerable< object > GetServices(Type serviceType) { return container.ResolveAll(serviceType); } } |
2:在Application_Start中注册
代码如下:
1 2 3 4 5 6 7 8 9 | using (IUnityContainer container = new UnityContainer()) { UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection( "unity" ); section.Configure(container, "containerOne" ); //tell mvc use UnityDependencyResolver to create controll instances; container.RegisterType<IControllerFactory, UnityControllerFactory>(); //_container.RegisterType<ISubjectRepository, SubjectRepository>(new TransientLifetimeManager()); DependencyResolver.SetResolver( new UnityDependencyResolver(container)); } |
3:Web.config配置如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <configSections> <section name= "unity" type= "Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration" /> </configSections> <assembly name= "SampleProject" /> < namespace name= "SampleProject" /> <alias alias= "ISampleClass" type= "ISampleClass" /> <alias alias= "SampleClass" type= "SampleClass" /> <container name= "containerOne" > <register type= "ISampleClass" mapTo= "SampleClass" /> </container> </unity> |
至此,完成本文所述功能。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步