No need for ViewModelLocator if using RegisterForNavigation? - prism

In prism we can have ViewModelLocator resolve the VM when we navigate to a View by setting the attached property prism:ViewModelLocator.AutowireViewModel="True"
However, in the PRISM samples on Github, the container is initialized using the extension method (RegisterForNavigation) which seems to do the same thing.... ,
containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>();
I am wondering if the RegisterForNavigation has made the AutowireViewModel attached property approach obsolete?

I am wondering if the RegisterForNavigation has made the AutowireViewModel attached property approach obsolete?
No, this kind of registration just - additionally - defines the view model to be used for the registered view directly (instead of relying on the convention configured in the view model locator).
Setting ViewModelLocator.AutowireViewModel is still required to actually create the view model (whether it's type is defined manually or derived from the view's type by a convention).

Related

Is there a simple way to auto register [Exports] in a Prism app? WPF .NET 4.8

I used to be on a project that used Prism and when we needed a new service to do something, we'd just create an interface, a concrete class that implemented that interface and exported it, and then it just became available everywhere for [ImportingConstructor]. We didn't need to manually register it or anything. I no longer have access to that project, but I don't think there was any reflection magic that was done manually to accomplish this.
I'm in a new company and we are starting up a project using MEF / Prism and I'm trying to accomplish the same thing, but as of right now, I'm having to manually register items in order to import them. What am I missing?
I'm in .NET 4.8 WPF app
Additional info
we are basing our project from this website
https://prismlibrary.com/index.html
This is our app class
public partial class App
{
protected override Window CreateShell()
{
return Container.Resolve<ShellWindow>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<IStartupActionService, StartupActionService>();
containerRegistry.RegisterSingleton<IGeneralNavigationService, GeneralNavigationService>();
containerRegistry.RegisterSingleton<IExperimentSetupNavigationService, ExperimentSetupNavigationService>();
containerRegistry.RegisterSingleton<IProtocolSetupNavigationService, ProtocolSetupNavigationService>();
containerRegistry.RegisterSingleton<IOurProjectNavigationService, OurProjectNavigationService>();
containerRegistry.RegisterSingleton<IOurProjectUiService, OurProjectUiService>();
containerRegistry.RegisterManySingleton<WcfClientService>();
containerRegistry.RegisterSingleton<IControlClientService, ControlClientService>();
}
}
Why do I have to register each new service?
I've been reading about MEF, DryIoc, and others and I'm just not getting clear answers. Is there not a way to just have everything with an [Export] become immediately available for import?
Something else I need to do, that I think this whole registering thing is messing me up on is trying to come up with a way to have "dialogs" but tie them to a neutral class to make it more MVVM happy.
Dialog -> a region that pops open when you call a method. This method currently takes in a UserControl, assumed to have already been constructed and its ViewModel datacontext already attached.
What I would like to do and don't know how to start is
use a neutral container class to open one of these dialogs (similar to interaction request Notification
using attributes, attach an attribute to a view that indicates "I support this neutral container class" (assumed only one view per container)
this view supports [ImportingConstuctor] to bring in its ViewModel
the viewmodel itself supports [ImportingConstuctor] to bring in services needed
again, the desire to NOT need to register these items manually as we add them. Would like to add a service interface, the concrete class that [Export]s the interface and have it just available to the viewmodel and other services, and same for the views and viewmodels, export attribute tag them as necessary and have them just available to either/both grab an instance of them or manually create an instance of them and have their [ImportingConstructors] handled for me.

Prism IDisposable Autofac and Lifetime Scope

I am using Prism to navigate between views in my WPF application. One view in particular I've implemented with the IRegionMemberLifetime.KeepAlive => returns false; to create a new instance of the view every time we navigate to the view (we need to do this for display reasons). This view also hosts a custom win32 control that I need to do some cleanup in using IDisposable.Dispose. When I navigate to my view and then away from it, I'd expect Dispose to get called (to run cleanup). I was able to achieve this by implementing a custom region behavior as discussed here, https://github.com/PrismLibrary/Prism/issues/7. All this is working fine except everything gets marked for disposal but the GC doesn't actually get rid of anything. I'm using Autofac as my IOC container and after doing some research I've concluded the reason comes down to Autofac and lifetime scopes of IDisposables, https://nblumhardt.com/2011/01/an-autofac-lifetime-primer/. Basically Autofac holds references to the IDisposable and the GC won't get rid of the old view because of this. For instance I'm registering my view in the Module as _container.RegisterTypeForNavigation(); I'm not able to register this with any sort of lifetime and I'm not sure how I'd resolve this with a lifetime specified? When I call RegionManager.RequestNavigate I don't see any sort of overloads to specify lifetime? Any ideas would be appreciated.
RegisterTypeForNavigation essentially does builder.RegisterType(type).Named<object>(name); which you can do yourself, too, of course and apply any lifetime you desire. There's no magic in registering for navigation, RegisterTypeForNavigation is just a shorthand.
To make Autofac ignore the IDisposables, one can write
builder.RegisterType<SomeView>().Named<object>(typeof(SomeView).Name).ExternallyOwned();
From the docs:
Disabling Disposal
Components are owned by the container by default and will be disposed by it when appropriate. To disable this, register a component as having external ownership:
builder.RegisterType<SomeComponent>().ExternallyOwned();
The container will never call Dispose() on an object registered with external ownership. It is up to you to dispose of components registered in this fashion.
So extending #Haukinger answer. This is what finally worked for me:
//builder.RegisterTypeForNavigation<SomeView>();
builder.RegisterType<SomeView>().Named<object>
(typeof(SomeView).Name).ExternallyOwned();
That ExternallyOwned() signals to autofac that the user is going to handle calling dispose and that autofac shouldn't track the IDisposable.

What does exposeBinding do?

I have been using bindings without having ever heard of exposeBinding.
Is it only intended to plug-ins ?
What does exposeBinding do ?
Expose bindings are nothing special, it is just normal binding what you see in the Xcode. But why its named is expose binding becuase when you do any binding in the interface builder. It causes second binding automatically in the interface builder which is called expose binding.
For your understanding i have attached the screen shot in which inside binding inspector i have just bind file owner to the hidden in Availablity section and then you can see below automatically it created hidden2 inside Availablity section below. This new binding hidden2 is called exposed binding. And also the used of these binding values are then used together in returning the final value of the binding. Please follow the attached screen shot:-
From the doc.
exposeBinding:
Exposes the specified binding, advertising its availability.

should I be creating my objects manually or with InterfaceBuilder?

I am relatively new to Cocoa/Xcode and am not sure if I am structuring my application in the most "correct" way possible. I have a number of objects which are active the while time that the application is running. Should I be creating these objects manually or with Interface Builder?
The type of objects I am referring to:
"downloader" which is responsible for downloading files to disk
user interface updater which is responsible for updating the user interface to show the results of the downloaded file
Should I create these objects in IB and set up the connections between them with code?
It's really a matter of personal preference.
In my opinion IB only really good at laying out views, so I tend to only use IB for my view and my view controller, and I create everything else in code in the view controller's viewDidLoad or init method.
In your example, connecting the "downloader" object directly to the interface seems like an MVC violation, so I would keep the downloader out of my xib.
The "interface updater" would be connected tightly to the interface, so it could be in the nib, although unless I had a good reason not to I would probably just put that code into my view controller class.
If you are creating things in code, note that viewDidLoad/viewDidUnload can potentially be called a number of times, as the os loads and un-loads your views when they are not visible to save memory. So only put transient objects there... things that must exist for the life of the view controller should be created in the init/dealloc methods. Part of why I like to do most of my object creation in code, is the finer level of control you have over memory.
I typically build as much as I can in IB, and then switch to code when I run into the limitations of IB. It sounds like you should be able to create the UI you described in interface builder.

NSArrayController and referring to a shared, static, Core Data based library

Using this guide I have created a static library (let's call it AppCore) that can be shared between the Mac OS X and iOS versions of one app. This static library uses Core Data and the point of it is to share the model part and schema versioning between different implementations.
I created a NSPersistentDocument based project that will depend on this AppCore. In this project I added a reference to the .xcdatamodel file. Then I created a simple table view with add/remove buttons to edit an array of one entity type with the assisted "new core data entity" item. This created an instance of NSArrayController and the required bindings for the add/remove behaviour.
Now, everything seems to work fine when I'm using the default class for the Core Data entities (NSManagedObject) and I'm able to add new rows using the +/- buttons. However, when I change the entity implementation class to a custom one, I'm getting an error
Failed to create new object
This seems to come from the NSArrayController and it seems to be unable to instantiate the required entity. I can, however, create one in the NSPersistentDocument subclass by:
[NSEntityDescription insertNewObjectForEntityForName:#"SomeEntity" inManagedObjectContext:[self managedObjectContext]]
What confuses me is why the instance of NSArrayController can't. If I understand correctly, the array controller is instructed to create an entity, not class and my guess is that the entities are created with the help of NSEntityDescription class. I could implement my own version of the array controller's add: but then again, it might be that here something is fundamentally wrong. I haven't touched the init:s and the custom entity class implementation is simply for convenience, to access the attributes directly.
I have tried changing the base SDK on the AppCore but without effect. Currently it uses the iOS version but I'm not sure how it should be. This is another question but if unrelated, I might ask it here on a separate question.
So, to summarize, why can't the NSArrayController create an instance of this entity?
Thanks in advance.
Update
This works if I add the SomeEntity class from the AppCore to the dependent project as a reference. This is not the most usable way since modifications to the AppCore has to be propagated to the dependatnt projects also.
Bingo. I missed the "-ObjC" flag for the dependant project's "other linker flags". Now everything works like a charm.

Resources