MVC TIP8:为控制器增加有参构造函数(为了注入等其它用途)

控制器本身是不带有参的构造函数的,如果我们为控制器仅仅提供有参的构造函数,就会报错。不过,可以利用DependencyResolver的SetResolver方法,让ASP.NET MVC支持有参的构造函数。

1:为系统准备两个类型,如下:

image

注意,这里要实现的是让控制器支持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>

至此,完成本文所述功能。

posted @   陆敏技  阅读(2365)  评论(0编辑  收藏  举报
Web Counter
Coupon for Contacts
点击右上角即可分享
微信分享提示