Adding Tabs to an application I realize that my child views are not disposed (finalized) after I remove them from the Region.
regionManager.Regions[regionName].Remove(tabItem.Content);
Everytime close the Tab and reopen it, a new instance is created correctly, but the old instance keeps open until I close the application. Checkt it via Finalizer Breakpoint. This causes my application not to release the Region and crash when RegionManager tries to create a region which already exists.
Even
[RegionMemberLifetime(KeepAlive = false)]
will remove it from the Region, but the object is still alive.
I had a similar issue and i just solved it this morning.
Just before adding the new Region with regionManager check if it doesn't already exist using:
this.regionManager.Regions.ContainsRegionWithName("Your region name")
Then, when i remove the view from the region, i just invoke garbage collector GC.Collect() method to "Dispose" the removed views and free memory.
However make sure that you use the attribute [RegionMemberLifetime(KeepAlive = false)] on your view.
For more information, see this post
Edit
Another solution, using Disposable pattern that i use also for some views.
Where my view implement IDisposable interface, then the method looks as the following:
public void Dispose()
{
GC.SuppressFinalize(this);
}
After that, when you remove the view from the Region, just invoke Dispose method :
myRegion.Deactivate(view);
myRegion.Remove(view);
var disposable = view as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
Note that i'm using mvvm pattern, and i don't have to free any another managed object, Otherwise, if you have some managed objects inside your view, please see more about IDisposable pattern here
Related
I've started a project using MVVM Light and have run into an issue where once a window is created a ViewModel is bound to it, however, if I close this window and reopen the same window another viewmodel is made.
Through the debugger I can see the code looping through properties and methods after interacting with forms. I can see many instances of the same collections/properties/methods being fired. This then creates errors of 'Out of Bounds" after deleting items, etc.
*Note: Using ViewModelLocator, bound within XAML and completely removed from the XAML.cs files. ViewModels not referenced anywhere else.
I've attempted the following. No Help.
(WPF/MVVM) Single Instance In MainViewModel
How should I handle this to eliminate multiple ViewModels and looping properties/methods. Methods/properties should only be looped once.
EDIT
I've solved my issue. By referencing a static class within windows resources I was creating a new instance per ListView. Thus forcing the ViewModel to loop to conditions to meet those instances each form that consumed an instance.
By eliminating the resource and moving all data to MVVM Light DataService and using Task from System.Threading.Tasks, I am able to bind to a collection within the ViewModel rather than a independent instance. No more looping. Thanks for the answers.
It's common to use viewmodel first and a single window application rather than multiple windows with their own viewmodels.
Partly since it's quite easy for users to "lose" multiple windows. It also closes off a number of sharing issue edge cases where you have window X open and when you open window Y the processing clashes.
With what you have now, one simple way round this is to use SimpleIOC to provide your viewmodels.
SimpleIOC gives you singletons for anything you ask for.
You may have seen code does:
SimpleIoc.Default.GetInstance<vmType>();
Which of course has a definite type inside those angle brackets.
An alternative is:
SimpleIoc.Default.GetInstance(vmType);
Where vmType can be a variable. A Type variable which matches the tupe of the viewmodel you want.
You could make a markup extension which takes a type as parameter and makes that call, returning the viewmodel.
I've not tried it, but I don't think you even need to register the type using that syntax.
You can always use Singleton Design Pattern
public sealed class Vm
{
//Private Constructor.
private Vm()
{
}
private static Vm instance = null;
public static Vm Instance
{
get
{
if (instance == null)
{
instance = new Vm();
}
return instance;
}
}
}
This is a small question, just to make sure I'm understanding Unity correctly.
I'm using Unity in an ASP.NET MVC application, and I have registered a type as follows:
container.RegisterType<IPizzaService, PizzaService>();
And I'm using it in a controller like:
public class PizzaController : Controller
{
private IPizzaService _pizzaService;
public PizzaController(IPizzaService pizzaService)
{
_pizzaService = pizzaService;
}
[HttpGet]
public ActionResult Index()
{
var pizzasModel = _pizzaService.FindAllPizzas();
...
}
}
Every time a page request is done, a new instance of IPizzaService is injected and used. So this all works fine.
My question: do I have to do anything special to dispose this instance? I assume that, once the request has ended, the controller is disposed and the PizzaService instance eventually gets garbage collected.
If I need deterministic disposal of an instance because it uses an entity framework context or an unmanaged resource for example, I have to override Dispose of the controller, and there make sure I call the dispose of the instances myself.
Right? If not, please explain why :)
Thanks!
IMO, whatever creates a disposable object is responsible for disposing it. When the container injects a disposable object via RegisterType<I, T>(), I want to guarantee that the object is ready to be used. However, using RegisterInstance<I>(obj) does dispose of your object automatically.
This can be difficult with an IOC container, and is impossible with Unity out of the box. However, there is some really nifty code out there that I use all the time:
http://thorarin.net/blog/post/2013/02/12/Unity-IoC-lifetime-management-IDisposable-part1.aspx
The blog has code for a DisposingTransientLifetimeManager and DisposingSharedLifetimeManager. Using the extensions, the container calls Dispose() on your disposable objects.
One caveat is that you'll need to reference the proper (older) version of Microsoft.Practices.Unity.Configuration.dll & Microsoft.Practices.Unity.dll.
ContainerControlledTransientManager was added in Unity on Jan 11, 2018
Add container 'owned' transient lifetime manager ContainerControlledTransientManager #37
So, ContainerControlledTransientManager is required. This lifetime manager is the same as TransientLifetimeManager except if the object implements IDisposable it will keep strong reference to object and dispose it when container is disposed.
If created object is not disposable, container does not maintain any object references so when that object is released GC will collect it immediately.
I have a site which uses a C# class file, and at the top of the file, I have:
JTSEntities database = new JTSEntities(); (an ADO.NET thingy).
I have it right up the top because I don't really feel like writing the same thing over and over again.
But it raises one question... Because it's up the top there, how will it get disposed, and when - and how can I dispose of it (or do I need to) when the user closes the page?
It is bad practice to hold on to anything that wraps a database connection for longer than needed.
The best practice would be to release the database connection as soon as it is no longer needed for the current operation (such as populating initial values, etc.), e.g. something like
using (JTSEntities database = new JTSEntities())
{
// Use database
}
if it implements IDisposable.
If for some reason you must keep it alive for the duration of the page, be sure you call an appropriate method to release resources (.Close(), .Dispose(), etc.) in the page close event handler.
Ok so, based on the type of the attribute, we can say that it's an instance attribute. This means that this attribute will have the same lifecyle as the object that has it, unless its instance is passed to another object.
If it's protected, then only the owner object and its childs (that is, objects that inherit from this class) will have access to it. If you don't pass it as a reference argument, then we're ok with the first statement: it will be cleaned by the GC as soon as the object is cleaned.
If you just use this object on a regular webform page lifecycle, then you don't have to worry with disposing it. The page lifecycle will do it for you.
Regards
Implement IDisposable in this class and dispose of this object inside the Dispose() method. When using this class, make sure you call Dispose when you are done (preferably with a using block)
Beyond that, you don't need to worry about it.
public class MyClass : IDisposable
{
protected JTSEntities database = new JTSEntities();
public void Dispose()
{
database.Dispose();
}
}
// When calling this class
using(MyClass cls = new MyClass())
{
// Do Stuff
} // Dispose is automatically called here.
I know that similar question was asked several times (for example: here, here,here and here) but it was for previous versions of Unity where the answer was dependent on used LifetimeManager class.
Documentation says:
Unity uses specific types that inherit
from the LifetimeManager base class
(collectively referred to as lifetime
managers) to control how it stores
references to object instances and how
the container disposes of these
instances.
Ok, sounds good so I decided to check implementation of build in lifetime managers. My conclusion:
TransientLifetimeManager - no handling of disposing. Container only resolves instance and it does not track it. Calling code is responsible for disposing instance.
ContainerControlledLifetimeManager - disposes instance when lifetime manager is disposed (= when container is disposed). Provides singleton instance shared among all containers in hiearchy.
HierarchicalLifetimeManager - derives behavior from ContainerControlledLifetimeManager. It provides "singleton" instance per container in hiearchy (subcontainers).
ExternallyControlledLifetimeManager - no handling of disposing. Correct behavior because container is not owner of the instance.
PerResolveLifetimeManager - no handling of disposing. It is generally same as TransientLifetimeManager but it allows reusing instance for dependency injection when resolving whole object graph.
PerThreadLifetimeManager - no handling of disposing as also described in MSDN. Who is responsible for disposing?
Implementation of build-in PerThreadLifetimeManager is:
public class PerThreadLifetimeManager : LifetimeManager
{
private readonly Guid key = Guid.NewGuid();
[ThreadStatic]
private static Dictionary<Guid, object> values;
private static void EnsureValues()
{
if (values == null)
{
values = new Dictionary<Guid, object>();
}
}
public override object GetValue()
{
object result;
EnsureValues();
values.TryGetValue(this.key, out result);
return result;
}
public override void RemoveValue()
{ }
public override void SetValue(object newValue)
{
EnsureValues();
values[this.key] = newValue;
}
}
So disposing container does not dispose disposable instances created with this lifetime manager. Thread completion will also not dispose those instances. So who is responsible for releasing instances?
I tried to manually dispose resolved instance in code and I found another problem. I can't teardown the instnace. RemoveValue of lifetime manager is empty - once the instance is created it is not possible to remove it from thread static dictionary (I'm also suspicious that TearDown method does nothing). So if you call Resolve after disposing the instance you will get disposed instance. I think this can be quite big problem when using this lifetime manager with threads from thread pool.
How to correctly use this lifetime manager?
Moreover this implementation is often reused in custom lifetime managers like PerCallContext, PerHttpRequest, PerAspNetSession, PerWcfCall, etc. Only thread static dictionary is replaced with some other construct.
Also do I understand it correctly that handling disposable objects is dependent on lifetime manager? So the application code is dependent on used lifetime manager.
I read that in other IoC containers dealing with temporary disposable objects is handled by subcontainers but I didn't find example for Unity - it could be probably handled with local scoped subcontainer and HiearchicalLifetimeManager but I'm not sure how to do it.
There are only a few circumstances where Unity will dispose an instance. It is really unsupported. My solution was a custom extension to achieve this - http://www.neovolve.com/2010/06/18/unity-extension-for-disposing-build-trees-on-teardown/
Looking at the Unity 2.0 source code, it smells like the LifetimeManagers are used to keep objects in scope in different ways so the garbage collector doesn't get rid of them. For example, with the PerThreadLifetimeManager, it will use the ThreadStatic to hold a reference on each object with that particular thread's lifetime. However, it won't call Dispose until the container is Disposed.
There is a LifetimeContainer object that is used to hold onto all the instances that are created, then is Disposed when the UnityContainer is Disposed (which, in turn, Disposes all the IDisposables in there in reverse chronological order).
EDIT: upon closer inspection, the LifetimeContainer only contains LifetimeManagers (hence the name "Lifetime"Container). So when it is Disposed, it only disposes the lifetime managers. (and we face the problem that is discussed already).
I came across this issue recently myself as I was instrumenting Unity into my application. The solutions I found here on Stack Overflow and elsewhere online didn't seem to address the issue in a satisfactory way, in my opinion.
When not using Unity, IDisposable instances have a well-understood usage pattern:
Within a scope smaller than a function, put them in a using block to get disposal "for free".
When created for an instance member of a class, implement IDisposable in the class and put clean-up in Dispose().
When passed into a class's constructor, do nothing as the IDisposable instance is owned somewhere else.
Unity confuses things because when dependency injection is done properly, case #2 above goes away. All dependencies should be injected, which means essentially no classes will have ownership of the IDisposable instances being created. However, neither does it provide a way to "get at" the IDisposables that were created during a Resolve() call, so it seems that using blocks can't be used. What option is left?
My conclusion is that the Resolve() interface is essentially wrong. Returning only the requested type and leaking objects that need special handling like IDisposable can't be correct.
In response, I wrote the IDisposableTrackingExtension extension for Unity, which tracks IDisposable instances created during a type resolution, and returns a disposable wrapper object containing an instance of the requested type and all of the IDisposable dependencies from the object graph.
With this extension, type resolution looks like this (shown here using a factory, as your business classes should never take IUnityContainer as a
dependency):
public class SomeTypeFactory
{
// ... take IUnityContainer as a dependency and save it
IDependencyDisposer< SomeType > Create()
{
return this.unity.ResolveForDisposal< SomeType >();
}
}
public class BusinessClass
{
// ... take SomeTypeFactory as a dependency and save it
public void AfunctionThatCreatesSomeTypeDynamically()
{
using ( var wrapper = this.someTypeFactory.Create() )
{
SomeType subject = wrapper.Subject;
// ... do stuff
}
}
}
This reconciles IDisposable usage patterns #1 and #3 from above. Normal classes use dependency injection; they don't own injected IDisposables, so they don't dispose of them. Classes that perform type resolution (through factories) because they need dynamically created objects, those classes are the owners, and this extension provides the facility for managing disposal scopes.
would it be a viable solution to use the HttpContext.Current.ApplicationInstance.EndRequest event to hook to the end of the request and then disposing of the object stored in this lifetime manager? like so:
public HttpContextLifetimeManager()
{
HttpContext.Current.ApplicationInstance.EndRequest += (sender, e) => {
Dispose();
};
}
public override void RemoveValue()
{
var value = GetValue();
IDisposable disposableValue = value as IDisposable;
if (disposableValue != null) {
disposableValue.Dispose();
}
HttpContext.Current.Items.Remove(ItemName);
}
public void Dispose()
{
RemoveValue();
}
you don't have to use a child container like the other solution and the code used to dispose the objects is still in the lifetime manager like it should.
I have a simple WPF single window application contains Textboxes and Buttons. And I also use NotifyIcon and DateTimePicker of Windows Forms in WPF window. How can I effectively dispose all the controls?
Hardly anything in WPF has a Dispose method. The vast majority of classes encapsulate purely managed information. You can attach an object into the tree (e.g. via a Children.Add method) and you can remove it again - that's how the state management works. It exactly doesn't fit into the IDisposable pattern, because once you've removed a control you can add it again, whereas Dispose means forever (although you could use Dispose to manage it in addition to Add/Remove methods).
A discussion about it on the Microsoft forums.
There are a few things that ought to be IDisposable but aren't, like DispatcherTimer, and there's nothing to stop you from implementing IDisposable on your own classes. It's up to you when to call Dispose; basically when you know you aren't going to be using the object any more.
For a Window you just call Close to close it, and WPF takes care of everything else.
I would say that the same rule applies in WPF applications as in any other .NET applications: if an object implements IDisposable, you should call Dispose when you are done using it. If you dynamically load and unload controls, and they do not implement IDisposable, just setting any references to null (and detaching any event handlers) should be enough for the garbage collector to do its job.
Adhere to CA1001: Let the owning type implement IDisposable.
Renounce the old Windows Forms truth that all controls are IDisposable. Implement and call Dispose yourselves.
sealed partial class MainWindow : IDisposable {
readonly IDisposable disposable;
public MainWindow() {
disposable = ...
}
public void Dispose() {
disposable.Dispose();
}
protected override void OnClosed(EventArgs e) {
Dispose();
base.OnClosed(e);
}
}
If that control is a part of some IContainer (that's the common model in .NET) than your controls just needs implementation of IDisposable. Thus Dispose() will be called automatically when it is appropriate time.