在ASP.Net MVC中实现Unity的正确方法是什么?

时间:2011-02-22 07:00:02

标签: c# asp.net-mvc-2 dependency-injection unity-container

好的,当你搜索这个主题时谷歌有这么多的结果; NerdDinnerCodeClimberCodeProject等。但他们似乎都没有按预期工作!他们在构建或运行时给出错误!在ASP.Net MVC 2中实现Unity 2.0的正确方法是什么?我根本无法做到这一点!

非常感谢您的帮助和想法。谢谢!

2 个答案:

答案 0 :(得分:3)

尝试使用Unity编写一个简单的控制器工厂,它能够解析控制器实例:

public class UnityControllerFactory : DefaultControllerFactory 
{
    private readonly IUnityContainer _container; 
    public UnityControllerFactory(IUnityContainer container) 
    { 
        _container = container; 
    }

    protected override IController GetControllerInstance(
        RequestContext requestContext, 
        Type controllerType
    ) 
    { 
        if (controllerType == null)
        {
            throw new ArgumentNullException("controllerType");
        }
        if (!typeof(IController).IsAssignableFrom(controllerType))
        {
            throw new ArgumentException("Type requested is not a controller", "controllerType");
        }
        return _container.Resolve(controllerType) as IController; 
    }
}

然后将其连接到Application_Start中的Global.asax事件:

protected void Application_Start()
{
    ...
    var container = new UnityContainer();
    // TODO: Configure the container here with your controllers

    var factory = new UnityControllerFactory(container);
    ControllerBuilder.Current.SetControllerFactory(factory);
}

答案 1 :(得分:1)

这是我UnityControllerFactory的版本。它使用反射从调用程序集中获取控制器并将它们注册到容器中。

using System;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace WebProveidorsMVC.DI.ControllerFactories
{
    public class UnityControllerFactory : DefaultControllerFactory
    {
        private readonly IUnityContainer _container;

        public UnityControllerFactory()
        {
            _container=new UnityContainer();

            ((UnityConfigurationSection) ConfigurationManager.GetSection("unity")).Configure(_container);

            var controllerTypes = from t in Assembly.GetCallingAssembly().GetTypes()
                                  where typeof(IController).IsAssignableFrom(t)
                                  select t;

            foreach (var t in controllerTypes)
                _container.RegisterType(t, t.FullName);
        }

        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            if (controllerType != null)
                return (IController)_container.Resolve(controllerType);
            return null;
        }

        public override void ReleaseController(IController controller)
        {
            _container.Teardown(controller);
            base.ReleaseController(controller);
        }
    }
}

然后在我的ApplicationStart方法中,我将其注册为:

ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory());