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

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

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

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

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

  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <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>

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

MVC TIP8:为控制器增加有参构造函数(为了注入等其它用途)本文基于Creative Commons Attribution 2.5 China Mainland License发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名http://www.cnblogs.com/luminji(包含链接)。如您有任何疑问或者授权方面的协商,请给我留言。
上一篇:Windows 8.1支持全新文件系统ReFS


下一篇:[转贴]使用jQuery自动缩图片 - [jQuery]