控制器本身是不带有参的构造函数的,如果我们为控制器仅仅提供有参的构造函数,就会报错。不过,可以利用DependencyResolver的SetResolver方法,让ASP.NET MVC支持有参的构造函数。
1:为系统准备两个类型,如下:
注意,这里要实现的是让控制器支持Unity注入。
UnityControllerFactory代码如下:
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代码如下:
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中注册
代码如下:
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配置如下
<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> |
至此,完成本文所述功能。
本文转自最课程陆敏技博客园博客,原文链接:http://www.cnblogs.com/luminji/archive/2011/12/22/2298262.html,如需转载请自行联系原作者