2

我正在开发一个使用 Unity 2.0 作为 IoC 容器的 ASP.Net MVC 3 Web 应用程序。

下面显示了我的Global.asax文件中的Application_Start()方法的示例

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    IUnityContainer container = new UnityContainer();

    container.RegisterType<IControllerActivator, CustomControllerActivator>(
        new HttpContextLifetimeManager<IControllerActivator>());

    //container.RegisterType<IUnitOfWork, UnitOfWork>(
    //  new ContainerControlledLifetimeManager());
    container.RegisterType<IUnitOfWork, UnitOfWork>(
        new HttpContextLifetimeManager<IUnitOfWork>());

    container.RegisterType<IListService, ListService>(
        new HttpContextLifetimeManager<IListService>());
    container.RegisterType<IShiftService, ShiftService>(
        new HttpContextLifetimeManager<IShiftService>());

    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

我的HttpContextLifetimeManager看起来像这样

public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
{
    public override object GetValue()
    {
        return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
    }

    public override void RemoveValue()
    {
        HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);
    }

    public override void SetValue(object newValue)
    {
        HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] =
            newValue;
    }

    public void Dispose()
    {
        RemoveValue();
    }
}

我的问题是,当我在上面设置断点时,永远不会调用上述类中的方法Dispose() 。我担心我的 IoC 容器实例永远不会被处理掉。这会导致问题吗?

我找到了我放在Global.asax文件中的这段代码,但仍然没有调用Dispose()方法

protected void Application_EndRequest(object sender, EventArgs e)
{
    using (DependencyResolver.Current as IDisposable);
}

谁能帮助我处理我的 Unity 容器的每个实例?

谢谢。

4

2 回答 2

3

使用 Unity.MVC3 nuget 包。然后在初始化时指定 HierarchicalLifetimeManager 并且您的对象将在每次请求后被处理。

container.RegisterType(new HierarchicalLifetimeManager());

就这么简单 : )

于 2012-07-26T16:40:25.410 回答
2

Unity 不会跟踪它创建的实例,也不会处理它们。Rory Primrose 有一个扩展,可以进行跟踪并允许通过调用来处理对象container.TearDown()

LifetimeManagers自己清理后的内容在Unity vNext 的愿望清单上

如果您对每个请求都进行引导,那么引导新容器实例的成本会很高。因此,在完成所有注册后,我会考虑缓存容器实例。

于 2012-07-26T16:06:32.320 回答