2
votes

I`m learning the concepts of composite applications. I created prism application using unity container. One of my regions configed as content control - In this Region, I want show just single view.

I`m using view injection in the next way:

object lastView;

    // View injection
    IRegion region = regionManager.Regions["MainRegion"];

    var ordersView = container.Resolve<OrdersView>();
    lastView = ordersView;
    region.Add(ordersView, "OrdersView");
    region.Activate(ordersView);

This the views in this region are switched frequently. Before Im switching view Im using region.remove(lastView) and than adding the next view like the code above.

Im not sure that its a good implementation, I have a few questions: When I`m using region.remove method, Is the removed view being disposed? Because if not after long run I will have serious memory leaks. What is the best way implement single view in a region while avoiding memory leaks?

Thanks

1

1 Answers

4
votes

By memory leaks I guess you're talking about whether the Garbage Collector is going to collect that view or not - e.g. is the container still referencing it when you remove it.

The decision on whether to keep a reference of the object after it's resolved is based on the type of the LifeTime Manager you used when you registered that object.

To answer your question shortly - The default LifeTime manager used with RegisterType is the TransientLifetimeManager, in which Unity creates a new instance of the requested type for each call to the Resolve or ResolveAll method.

What you're probably looking for is the ExternallyControlledLifetimeManager:

This lifetime manager allows you to register type mappings and existing objects with the container so that it maintains only a weak reference to the objects it creates when you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes based on attributes or constructor parameters within that class. This allows other code to maintain the object in memory or dispose it and enables you to maintain control of the lifetime of existing objects or allow some other mechanism to control the lifetime.

If you want to control the lifetime of your views, consider using the RegisterType with this LifeTime Manager.

Also, according to this article - The only lifetime managers which calls Dispose on resolved instances are ContainerControlledLifetimeManager (which creates singelton instances) and HierarchicalLifetimeManager. In these cases, the Dispose is only called when the lifetime manager is disposed.