How can I check that a MEF CompositionContainer does not maintain a reference to a non-shared part? - .net-4.5

I am using MEF in a WPF application. I use MEF to create view model objects for my views, and am interested in avoiding memory leaks by ensuring that the MEF CompositionContainer does not keep references to my view model objects.
I am aware of this question and its answers. I carefully avoid using IDisposable, since it doesn't "play nicely" with WPF.
For debug purposes, I would like to write some code that asserts that an object has not been added to the CompositionContainer. This would ensure that I haven't made a subtle change to a view model class that means that it is now not properly being released.
Here is some sample code. How can I implement AssertNotInContainer? Note that in this example it would be trivial to dispose of exportLifetimeContext properly. However, in my more complex scenario I want to be able to rely on the garbage collector rather than IDisposable, since it is hard to determine the lifetime of WPF objects and their associated view models (attached by the DataContext).
namespace Demo
{
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
CompositionContainer container = new CompositionContainer(new ApplicationCatalog());
MyOwnerClass demo = container.GetExport<MyOwnerClass>().Value;
// Not going to dispose this...
ExportLifetimeContext<MyLittleClass> exportLifetimeContext = demo.Factory.CreateExport();
// Note that I don't dispose of exportLifetimeContext, since I know that if MyLittleClass obeys
// the proper rules, it won't be added to the container anyway, and exportLifetimeContext.Dispose()
// will do nothing anyway.
MyLittleClass part = exportLifetimeContext.Value;
// I wan't this to assert that part is not referenced in container.
container.AssertNotInContainer(part);
// This is a hacky way that I can confirm that MyLittleClass isn't referenced by the container.
// This causes "Finalized." to be sent to the console.
GC.Collect();
Console.ReadLine();
}
}
[Export]
public class MyOwnerClass
{
[Import]
public ExportFactory<MyLittleClass> Factory { get; set; }
}
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class MyLittleClass
{
~MyLittleClass()
{
Console.WriteLine("Finalized.");
}
}
public static class MefHelper
{
[Conditional("DEBUG")]
public static void AssertNotInContainer(this CompositionContainer container, object part)
{
// What code should I write here?
bool isInContainer = false /* ??? */;
if (isInContainer)
{
throw new InvalidOperationException(
"Part does not meet rules for not being added to CompositionContainer. You have a leak!");
}
}
}
}
MEF Part Lifetime
The MEF documentation includes a useful, though out-of-date, page explaining the lifetime of objects created by MEF. It says the following:
We believe that .Net Garbage Collector is the best thing to rely on for proper clean up. However, we also need to provider a container that has a deterministic behavior. Thus, the container will not hold references to parts it creates unless one of the following is true:
The part is marked as Shared
The part implements IDisposable
One or more imports is configured to allow recomposition

Related

Dagger and Object Graph Scoping with Flow/Mortar

So I've been spending a lot of time with Mortar and Flow this weekend, and I think I've finally worked most of it out. I've found that it's a little bit more complex than I originally thought, mostly because I haven't quite gotten my mind around Dagger's ObjectGraph Scoping, which Mortar relies on heavily. I've read as much as I could find on this on Dagger's site, but I find information on this subject lacking when it relates specifically to Dagger.
So I have a few questions:
1. I see examples of them scoping #Singleton's:
#Layout(R.layout.screen_friend)
public class FriendScreen implements Blueprint {
#Override public String getMortarScopeName() {
return getClass().getName();
}
#Override public Object getDaggerModule() {
return new Module();
}
#dagger.Module(
injects = FriendView.class
)
static class Module {
}
#Singleton
public static class Presenter extends ViewPresenter<TestView> {
#Inject
public Presenter() {
Log.d("FriendScreen", "Friend Presenter Created");
}
#Override protected void onLoad(Bundle savedInstanceState) {
super.onLoad(savedInstanceState);
}
}
Is Presenter in this case scoped to this Module specifically because it's an inner class?
2. How can I make sure that an instance of it is only created in this Object Graph but not the global application object graph?
2. What if the Presenter was too big, and I wanted to move it to it's own separate class? How would I scope it just to this module?
3. I noticed that some of the Module classes in their examples are static, and others aren't. Does this have any effect on scoping?
4. Where can I read more to better understand Dagger's Object Graph. I need to get a better understanding of includes, injects, addsTo and how those are used in ObjectGraph creation
etc:
#dagger.Module( //
includes = ActionBarModule.class,
injects = MainView.class,
addsTo = ApplicationModule.class, //
library = true //
)
I don't believe presenters are scoped to a module since on a rotation they are preserved. the #Singleton annotation also leads me to believe that a presenter is on a global graph and just binds to a view when an activity recreates itself.
Here's a good scoping source.
Effective Java has a fantastic explanation about static inner vs non static inner vs anonymous classes if you want to learn more about those.

Singleton pattern using PHP

I am trying to create a dynamic navigation class.
class myApp_Helper_Breadcrum{
protected $navigationArray=array();
private static $_instance = null;
public static function getInstance()
{
if (!isset(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
private function __construct() {
$this->navigationArray = array();
}
public function popin($popInElement){
array_push($this->navigationArray,$popInElement);
}
public function displayLinks()
{
//print array
}
}
In boostrap I did following
$nlinks=myApp_Helper_Breadcrum::getInstance();
Zend_Registry::set('nlinks',$nlinks);
Now in my controller I am calling as follow
$nlinks= Zend_Registry::get('nlinks');
$nlinks->popin('Home');
$nlinks->displayLinks();
The problem is, even if this class is singleton the constructor is called again and again which makes my array to initialize. what I am trying to achieve is to keep pushing the items in the navigation array as I navigate the site.
Any idea why it is like this in ZF?
PHP isn't running like Java would where you have a JVM to maintain the state of your classes. In Java you can have a singleton behave exactly as you describe, but in PHP all the classes are refreshed with each subsequent call to the web server. So your singleton will stay in place for the duration of that call to the server, but once the response is sent then you start over again on the next call.
If you want to maintain state through successive calls you need to use the $_SESSION to keep track of your state.
EDIT:
My answer above deals with PHP in general and not the Zend Framework specifically. See my comment below.
Try to define your component as below:
class MyApp_Helper_Breadcrum
{
private static $_instance = null; // use private here
public static function getInstance()
{
if (self::$_instance === null) { // use strictly equal to null
self::$_instance = new self();
}
return self::$_instance;
}
private function __construct() // use private here
{
// ...
}
// ...
}
I ran into the exact same problem.
The problem is that the persistence of your classes are on the request scope.
And with zend, you can even have multiple requests for a page load.
PHP is a shared nothing architecture; each
request starts in a new process, and at the end of the request, it's all
thrown away. Persisting across requests simply cannot happen -- unless
you do your own caching. You can serialize objects and restore them --
but pragmatically, in most cases you'll get very little benefit from
this (and often run into all sorts of issues, particularly when it comes
to resource handles).
You may want to use Zend_cache, for persistence
Even though this is old, I would like to add my 2 cent.
Zend DOES NOT create a singleton, that persists across multiple requests. Regardless of the interpretation of the ZF documentation, on each request, the whole stack is re-initialized.
This is where your problem comes from. Since bootstrapping is done on each request, each request also re-initializes your helper method. As far as I know, helpers in ZF 1.x CAN'T be singletons.
The only way I see this being implementes ar you want it to be, is using sessions.

MVVM share object between the all the views

I have MVVM Project and I want to share one object( singleton ) from the model between several viewmodel what is the good practice to do that?
Thank you for the help
If the object is needed and does not provide value without it force the interface within the object via Constructor Injection; do not push a concrete type via injection always make use of an interface.
Since you are not making use of an IoC container such as Unity, you will need to create your singleton instance at the startup of your application and then make sure that the given instance is passed in via the given ViewModels constructor as needed.
A better approach would be pushing the singleton instance to a service which can provide the needed behavior and then disregard pushing the singleton into the Model. This would be a more MVVM purist approach and will separate concerns across your Models/ViewModels.
EDIT:
If you were making use of Unity you would define a Lifetime Manager at the time of registration.
// Register a type to have a singleton lifetime without mapping the type
// Uses the container only to implement singleton behavior
myContainer.RegisterType<MySingletonObject>(new ContainerControlledLifetimeManager());
// Following code will return a singleton instance of MySingletonObject
// Container will take over lifetime management of the object
myContainer.Resolve<MySingletonObject>();
Once you do this any attempt to resolve MySingletonObject via the IUnityContainer would resolve to the same instance providing the singleton behavior you so desire across the application. ViewModels themselves should not need to have the same instance returned. The data it needs should be abstracted away via a service as referenced earlier which could potentially behave like a singleton and provide a stateful implementation if needed but the ViewModel should not need to be a singleton. If you find yourself making either a Model or ViewModel a singleton; take a step back and analyze your design.
If you have control over all viewmodels then an easy approach (that I've used personally) is to just put a static variable on the base class of all viewmodels and make that accessible to all inheritors (either protected or even public if its useful outside of the viewmodels).
It's good practice anyway to have a common base class for your viewmodels since it allows you to implement property notification in one place (and other common functionality, like messaging etc.) instead of replicating it in all viewmodels.
Something like this is what I've used in my projects:
public class MyViewModelBase : INotifyPropertyChanged
{
private static MySharedSingleton _sharedObj;
static MyViewModelBase()
{
_sharedObj = new MySharedSingleton(/* initialize it here if needed */);
}
// or public
protected MySharedSingleton SharedObject { get { return _sharedObj; } }
// INotifyPropertyChanged stuff
// ...
}
public class SomeViewModel : MyViewModelBase
{
void SomeMethod()
{
SharedObject.DoStuff();
}
}
If the construction of the shared singleton object is heavy, you can of course use any of the standard techniques for lazy instantiation of it.
I would suggest that you inject the dependency into each view model (either constructor or property injection for example), and always work against abstractions in your view models, so that your dependency can easily be mocked or replaced as required. You then just need to ensure that each view model uses the same instance of your type - if you are using an IoC container, you can register a shared instance of your type easily.
I use a separate class for my global singleton with a model. This relieves me of agonizing over how to inject this model into view models and other models. E.g.
The singleton:
public class ApplicationModel
{
public string LoggedOnUser { get; set; }
// Etc.
private ApplicationModel() {
// Set things up.
}
private static ApplicationModel _active;
public static ApplicationModel Current {
get {
if (_active == null) {
_active = new ApplicationModel();
}
return _active;
}
}
}
The view model that needs to hold no reference to the singleton:
public class SomeViewModel
{
private string _user;
public SomeViewModel() {
_user = ApplicationModel.Current.LoggedOnUser;
}
}

ExportLifetimeContext<T>

Why does the ExportLifetimeContext<T> exist? What is it for? And why is it necessary to call Dispose on this objec at all? Do I really need to bother calling it? It doesn't feel very managed if I have to spend time thinking about resource managment, it doesn't feel very managed to me.
Is this dispose in anyway tied to the Value property? Is there a specific problem with just going CreateExport().Value?
When you ask an ExportFactory to create a new object, MEF might actually also create dependencies, and the dependencies of those dependencies, etcetera. Many objects might be created because you asked for a single object.
Some of these extra objects might be IDisposable, and the container is responsible for disposing those when they are no longer necessary.
To signal to the container that you are done using your object, you call ExportLifetimeContext<T>.Dispose(). The MEF container will then take care of disposing the requested object and its dependencies if necessary. If you don't do this, MEF will keep references to these objects forever, waiting for a signal that it can dispose them.
In Autofac 2, a very similar mechanism exists. Instead of ExportFactory, they use Func<Owned<T>> and you need to call Owned<T>.Dispose() to clean up.
edit: The MEF documentation has a Parts lifetime section where it is described in which cases exactly the container keeps references to exports. It does not yet mention ExportLifetimeContext.Dispose but I imagine this is similar to CompositionContainer.ReleaseExport.
edit: note that ExportFactory is intended for cases where you have a clearly defined lifetime. If this is not the case (or you know that clean-up is never necessary), then you should create your own factory implementation. Of course, it is then your responsibility to make sure that nothing IDisposable is created, since it would be impossible to clean it up properly.
Here is an example of a custom factory import/export using Func<T>.
[Export(typeof(ISomeInterface))]
public class SomeClass
{
private readonly Func<Foo> fooFactory;
[ImportingConstructor]
public SomeClass(Func<Foo> fooFactory)
{
this.fooFactory = fooFactory;
}
public void DoStuff()
{
Foo newFoo = fooFactory();
...
}
}
public class FooFactory
{
[Export(typeof(Func<Foo>))]
public void CreateFoo()
{
...
}
}

How do I use constructor dependency injection to supply Models from a collection to their ViewModels?

I'm using constructor dependency injection in my WPF application and I keep running into the following pattern, so would like to get other people's opinion on it and hear about alternative solutions.
The goal is to wire up a hierarchy of ViewModels to a similar hierarchy of Models, so that the responsibility for presenting the information in each model lies with its own ViewModel implementation. (The pattern also crops up under other circumstances but MVVM should make for a good example.)
Here's a simplified example. Given that I have a model that has a collection of further models:
public interface IPerson
{
IEnumerable<IAddress> Addresses { get; }
}
public interface IAddress
{
}
I would like to mirror this hierarchy in the ViewModels so that I can bind a ListBox (or whatever) to a collection in the Person ViewModel:
public interface IPersonViewModel
{
ObservableCollection<IAddressViewModel> Addresses { get; }
void Initialize();
}
public interface IAddressViewModel
{
}
The child ViewModel needs to present the information from the child Model, so it's injected via the constructor:
public class AddressViewModel : IAddressViewModel
{
private readonly IAddress _address;
public AddressViewModel(IAddress address)
{
_address = address;
}
}
The question is, what is the best way to supply the child Model to the corresponding child ViewModel?
The example is trivial, but in a typical real case the ViewModels have more dependencies - each of which has its own dependencies (and so on). I'm using Unity 1.2 (although I think the question is relevant across the other IoC containers), and I am using Caliburn's view strategies to automatically find and wire up the appropriate View to a ViewModel.
Here is my current solution:
The parent ViewModel needs to create a child ViewModel for each child Model, so it has a factory method added to its constructor which it uses during initialization:
public class PersonViewModel : IPersonViewModel
{
private readonly Func<IAddress, IAddressViewModel> _addressViewModelFactory;
private readonly IPerson _person;
public PersonViewModel(IPerson person,
Func<IAddress, IAddressViewModel> addressViewModelFactory)
{
_addressViewModelFactory = addressViewModelFactory;
_person = person;
Addresses = new ObservableCollection<IAddressViewModel>();
}
public ObservableCollection<IAddressViewModel> Addresses { get; private set; }
public void Initialize()
{
foreach (IAddress address in _person.Addresses)
Addresses.Add(_addressViewModelFactory(address));
}
}
A factory method that satisfies the Func<IAddress, IAddressViewModel> interface is registered with the main UnityContainer. The factory method uses a child container to register the IAddress dependency that is required by the ViewModel and then resolves the child ViewModel:
public class Factory
{
private readonly IUnityContainer _container;
public Factory(IUnityContainer container)
{
_container = container;
}
public void RegisterStuff()
{
_container.RegisterInstance<Func<IAddress, IAddressViewModel>>(CreateAddressViewModel);
}
private IAddressViewModel CreateAddressViewModel(IAddress model)
{
IUnityContainer childContainer = _container.CreateChildContainer();
childContainer.RegisterInstance(model);
return childContainer.Resolve<IAddressViewModel>();
}
}
Now, when the PersonViewModel is initialized, it loops through each Address in the Model and calls CreateAddressViewModel() (which was injected via the Func<IAddress, IAddressViewModel> argument). CreateAddressViewModel() creates a temporary child container and registers the IAddress model so that when it resolves the IAddressViewModel from the child container the AddressViewModel gets the correct instance injected via its constructor.
This seems to be a good solution to me as the dependencies of the ViewModels are very clear and they are easily testable and unaware of the IoC container. On the other hand, performance is OK but not great as a lot of temporary child containers can be created. Also I end up with a lot of very similar factory methods.
Is this the best way to inject the child Models into the child ViewModels with Unity?
Is there a better (or faster) way to do it in other IoC containers, e.g. Autofac?
How would this problem be tackled with MEF, given that it is not a traditional IoC container but is still used to compose objects?
Depending on the container can you not specify a parameter (named or otherwise) in your factory's CreateAddressViewModel method?
container.Resolve<IAddressViewModel>(new NamedParameterOverloads() { { "Address", model } };
Depending on the container your factory may have to know the name of the parameter (TinyIoC and Castle afaik), or it may had to be last in the list of constructor dependencies (YMMV depending on containers), which isn't great, but it saves creating a lot of child containers in quick succession, and the GC thrashing that will follow, and you still get DI for all your other dependencies.
Of course this falls down if your VM also has a dependency that requires the same IAddress, in that case a child container is probably the way to go unless you want the VM to have knowledge of the container.
Update:
If you're using a subcontainer of a container that uses "last register wins" (which I think Unity does), then you could pass the same child container into your Factory each time, and have your factory simply register the new IAddress - that way you wouldn't be creating a new UnityContainer instance on the heap for each iteration and it should cut down on garbage collections if you're creating lots of items.
The ViewModel sample application of the WPF Application Framework (WAF) shows how you could bring the Model and the ViewModel together. The sample uses MEF as Dependency Injection Framework.