In asp.net MVC2 using unity does my program need to manage the lifetime of the container?

浪子不回头ぞ 提交于 2019-12-24 07:46:12

问题


I'm putting the unity container creation/setup in the global.asax. and making the container a static property on that class since i'm not sure how unity works or if the container needs to be kept alive and references elsewhere. What's the recommended location of unity initialization/configuration for mvc 2?


回答1:


You shouldn't need to keep an explicit reference around for the container. A container should wire up the requested object graph (Controllers in this case) and get out of the way.

Take a look at the container-specific implementations of IControllerFactory in MVCContrib.

That said, I like the WindsorControllerFactory a lot better than the UnityControllerFactory, but you could implement a UnityControllerFactory that uses the same pattern (Constructor Injection) as the WindsorControllerFactory.

If you imagine that we do that, your Global.asax should look like this:

var container = new UnityContainer();

// configure container

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

controllerFactory holds a reference to the container, so you can let it go out of scope in Application_Start - it's going to stay around because the ControllerFactory stays around.




回答2:


Here's how we did it:

public class UnityControllerFactory : DefaultControllerFactory
{
    private IUnityContainer container;

    public UnityControllerFactory(IUnityContainer container)
    {
        this.container = container;
    }

    public static void Configure()
    {
        IUnityContainer container = new UnityContainer();
        //...Register your types here

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

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
        {
            return base.GetControllerInstance(requestContext, controllerType);
        }

        if (!typeof(IController).IsAssignableFrom(controllerType))
        {
            throw new ArgumentException("Type requested is not a controller", "controllerType");
        }

        return container.Resolve(controllerType) as IController;
    }
}

And then in global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        .... whatever you like
    }

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
        UnityControllerFactory.Configure();
    }
}


来源:https://stackoverflow.com/questions/2072121/in-asp-net-mvc2-using-unity-does-my-program-need-to-manage-the-lifetime-of-the-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!