MEF problem with import - wpf

models from shell-view-model with abstract factory pattern. I need inject in view-models classes from external assembly. If I use abstract factory pattern on creation view-models. Problem is imported classes in view-models are null.
Shell-view-models look like this:
public interface IViewModelFactory
{
ILogOnViewModel CreateLogOnViewModel(IShellViewModel shellViewModel);
IMessengerViewModel CreateMessengerViewModel(IShellViewModel shellViewModel);
}
[Export(typeof(IViewModelFactory))]
public class DefaulFactoryViewModel:IViewModelFactory
{
#region Implementation of IViewModelFactory
public ILogOnViewModel CreateLogOnViewModel(IShellViewModel shellViewModel)
{
return new LogOnViewModel(shellViewModel);
}
public IMessengerViewModel CreateMessengerViewModel(IShellViewModel shellViewModel)
{
return new MessengerViewModel(shellViewModel);
}
#endregion
}
public interface IShellViewModel
{
void ShowLogOnView();
void ShowMessengerView();
}
[Export(typeof(IShellViewModel))]
public class ShellViewModel : Conductor<IScreen>, IShellViewModel
{
private readonly IViewModelFactory _factory;
[ImportingConstructor]
public ShellViewModel(IViewModelFactory factory)
{
_factory = factory;
ShowLogOnView();
}
public void ShowLogOnView()
{
var model = _factory.CreateLogOnViewModel(this);
// var model = IoC.Get<LogOnViewModel>();
ActivateItem(model);
}
public void ShowMessengerView()
{
var model = _factory.CreateMessengerViewModel(this);
ActivateItem(model);
}
}
Some view-model.:
public class LogOnViewModel : Screen,ILogOnViewModel
{
[Import]//inject class from external assembly
private IPokecConnection _pokecConn;
private readonly IShellViewModel _shellViewModel=null;
private User _user=null;
public LogOnViewModel(IShellViewModel shellViewModel)
{
_shellViewModel = shellViewModel;
_user = new User();
}
}
variable _pokecConn are null becasuse I use abstract factory on creation new view-models.
if I use in shell-view model this:
var model = IoC.Get<LogOnViewModel>();
instead this:
var model = _factory.CreateLogOnViewModel(this);
and add Export attribute on view-models classes it works good, but I would like use abstract factory, and inject in view-model only classes from extrenal assembly.
It exist solution on this problem, or I must create view-models from IoC and export all class? Thanl for advance.
EDITED :
MEF BOOTSTRAPER CLASS:
public class MefBootStrapper : Bootstrapper<IShellViewModel>
{
#region Fields
private CompositionContainer _container;
#endregion
#region Overrides
protected override void Configure()
{ // configure container
#if SILVERLIGHT
_container = CompositionHost.Initialize(
new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>()));
#else
var catalog =
new AggregateCatalog(
AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>());
//add external DLL
catalog.Catalogs.Add(
new AssemblyCatalog(string.Format(
CultureInfo.InvariantCulture, "{0}{1}", System.IO.Directory.GetCurrentDirectory(), #"\Pokec_Toolkit.dll")));
_container = new CompositionContainer(catalog);
#endif
var batch = new CompositionBatch();
batch.AddExportedValue<IWindowManager>(new WindowManager());
batch.AddExportedValue<IEventAggregator>(new EventAggregator());
batch.AddExportedValue(_container);
_container.Compose(batch);
_container.SatisfyImportsOnce(this);
}
protected override object GetInstance(Type serviceType, string key)
{
string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
var exports = _container.GetExportedValues<object>(contract);
if (exports.Count() > 0)
return exports.First();
throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
}
protected override IEnumerable<object> GetAllInstances(Type serviceType)
{
return _container.GetExportedValues<object>(AttributedModelServices.GetContractName(serviceType));
}
protected override void BuildUp(object instance)
{
_container.SatisfyImportsOnce(instance);
}
#endregion
}

Did you forget the attribute ImportingConstructor for the LogOnViewModel constructor?
EDIT: Import property always null (MEF import issue)

Related

Navigation between lazy loaded modules with Prism and WPF

Hello I'm trying to setup an architecture where only one module gets booted when the app is launched. Then I'd like to lazy load other modules based on the user's actions.
To achieve this in my app.xaml.cs I have one module loaded at bootstrap time (MainModule), and an other has InitializationMode = InitializationMode.OnDemand
protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
{
Type BlipModuleType = typeof(BlipModule);
moduleCatalog.AddModule(new ModuleInfo()
{
ModuleName = BlipModuleType.Name,
ModuleType = BlipModuleType.AssemblyQualifiedName,
InitializationMode = InitializationMode.OnDemand
});
moduleCatalog.AddModule<MainModule>();
}
then my main module, which displays the view correctly, has a single view registered to the only region available:
public class MainModule : IModule
{
private readonly IRegionManager _regionManager;
public MainModule(IRegionManager regionManager)
{
_regionManager = regionManager;
}
public void OnInitialized(IContainerProvider containerProvider)
{
_regionManager.RegisterViewWithRegion(RegionNames.ContentRegion, typeof(ViewA));
}
public void RegisterTypes(IContainerRegistry containerRegistry)
{
}
}
The lazy loaded module has the same structure, registering a different view (which works properly if i decide to use it as my main module)
public class BlipModule : IModule
{
private readonly IRegionManager _regionManager;
public BlipModule(IRegionManager regionManager)
{
_regionManager = regionManager;
}
public void OnInitialized(IContainerProvider containerProvider)
{
_regionManager.RegisterViewWithRegion(RegionNames.ContentRegion, typeof(ViewB));
}
public void RegisterTypes(IContainerRegistry containerRegistry)
{
}
}
finally I have a Command in the viewmodel of my MainModule ViewA, that is supposed to load the new module and navigate to it.
public class ViewAViewModel : BindableBase
{
const string BlipModuleName = "BlipModule";
public ReactiveCommand ChangeRoute { get; set; } = new ReactiveCommand();
public ViewAViewModel(IRegionManager regionManager, IModuleManager moduleManager)
{
ChangeRoute.Subscribe(res =>
{
moduleManager.LoadModule(BlipModuleName);
});
moduleManager.LoadModuleCompleted += (s, e) =>
{
if (e.ModuleInfo.ModuleName == BlipModuleName)
{
regionManager.RequestNavigate(RegionNames.ContentRegion, new Uri(BlipModuleName, UriKind.Relative));
}
};
}
}
The viewB of the BlipModule is actually loaded (I get a hit if I set a breakpoint in the view's constructor), but instead of the view I get a white page with "System.Object" inside of it.
Any idea? thanks!
You want to RegisterForNavigation instead of RegisterViewWithRegion.

Update viewmodel based on MainWindow event

I have a UdpClient, firing off a DataRecevied event on my MainWindow:
public partial class MainWindow : Window
{
public static YakUdpClient ClientConnection = new YakUdpClient();
public ClientData;
public MainWindow()
{
InitializeComponent();
Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
ClientData = new ClientData();
ClientConnection.OnDataReceived += ClientConnectionOnDataReceived;
}
private void ClientConnectionOnDataReceived(object sender, MessageEventArgs messageEventArgs)
{
ClientData.Users = messageEvenArgs.ConnectedUsers;
}
}
My ClientData and User classes look as follow:
public class ClientData
{
public List<User> Users {get;set;)
}
public class User
{
public string Name {get;set;}
}
On my MainWindow, I have a UserControl called UserListView which has a ViewModel called UserListViewModel
The ViewModel looks as follow:
public class UserListViewModel: BindableBase
{
public UserListViewModel()
{
//I am sure there are better ways of doing this :(
Users = new ObservableCollection<User>((MainWindow)Application.Current.MainWindow).ClientData.Users
});
private ObservableCollection<User> _users;
public ObservableCollection<User> Users
{
get{ return _users;}
set { this.SetProperty(ref this._users, value); }
}
}
The difficulty I have here, is when the ClientConnectionOnDataReceived event on the MainWindow gets fired, I would like to update my ClientData class, My Viewmodel should then somehow be notified that the list changed, and subsequently update my UI.
Can anyone give me a solid example of how to achieve this using MVVM (Prism) in WPF?
I am new to MVVM, so i am still trying to figure this out.
First of all, there's no obvious reason why the main window should do the subscription.
I'd go for something like this:
create a service that encapsulates the subscription (and subscribes in its constructor)
register that as a singleton
have it implement INotifyPropertyChanged (to notify consumers of a change to Users)
inject the service into UserListViewModel and observe the Users property (see PropertyObserver)
when Users in the service changes, update Users in the user list view model
and best of all, no need for ObservableCollection here :-)
EDIT: example:
interface IUserService : INotifyPropertyChanged
{
IReadOnlyCollection<User> Users
{
get;
}
}
class YakUdpService : BindableBase, IUserService
{
private readonly YakUdpClient _yakUdpClient;
private IReadOnlyCollection<User> _users;
public YakUdpService()
{
_yakUdpClient = new YakUdpClient();
_yakUdpClient.OnDataReceived += ( s, e ) => Users = e.ConnectedUsers;
}
public IReadOnlyCollection<User> Users
{
get
{
return _users;
}
private set
{
SetProperty( ref _users, value );
}
}
}
class UserListViewModel : BindableBase
{
private IReadOnlyCollection<UserViewModel> _users;
private readonly IUserService _userService;
private readonly PropertyObserver<IUserService> _userServiceObserver;
public UserListViewModel( IUserService userService )
{
_userService = userService;
_userServiceObserver = new PropertyObserver<IUserService>( userService );
_userServiceObserver.RegisterHandler( x => x.Users, () => Users = _userService.Users.Select( x => new UserViewModel( x ) ).ToList() );
// ^^^ should use factory in real code
}
public IReadOnlyCollection<UserViewModel> Users
{
get
{
return _users;
}
private set
{
SetProperty( ref _users, value );
}
}
}
and then register the service
Container.RegisterType<IUserService, YakUdpService>( new ContainerControlledLifetimeManager() );
in your bootstrapper or your module's initialization.

Is this a good way of using ViewModelLocator in MVVM

WE have a ViewModelLocater class in our Silverlight App. It consist of a basic constructor and a public property to return the ViewModel for a class. The code is something like this
public class ViewModelLocator
{
private Dictionary<string, ViewModel> _viewModels =
new Dictionary<string, ViewModel>();
public ViewModelLocator()
{
_viewModels.Add("Home", HomeViewModel());
_viewModels.Add("Setup", new SetupViewModel());
_viewModels.Add("TasksActivities", new TasksActivitiesViewModel());
_viewModels.Add("Timesheet", new TimesheetViewModel());
}
public ViewModel this[string viewName]
{
get { return _viewModels[viewName]; }
}
}
and in each of the XAML pages we set the ViewModel for that page using
DataContext="{Binding [Setup], Source={StaticResource ViewModelLocator}}"
Setup is the key in the above dictionary.
The Silverlight App is really big and we have only recently started looking into any memory leaks(There are many...) I am using Windbg to track these leaks and I have noticed a lot of memory leaks leading back to the ViewModelLocater class. Every time the app loads the ViewModelLocator constructor creates ViewModels for all the Views. So I am wondering if there is a better way of implementing the ViewModelLocator class.
We use ViewModelLoader/ViewModelLocator to provide both DesignTime as well as Runtime DataContexts.
ViewModelLocator Class
public static class ViewModelLocator
{
public static readonly DependencyProperty FactoryProperty = DependencyProperty.RegisterAttached("Factory",
typeof (IViewModelFactory), typeof (ViewModelLocator),
new FrameworkPropertyMetadata(null, PropertyChangedCallback));
public static void SetFactory(DependencyObject dependencyObject, IViewModelFactory value)
{
dependencyObject.SetValue(FactoryProperty, value);
}
public static IViewModelFactory GetFactory(DependencyObject dependencyObject)
{
return (IViewModelFactory) dependencyObject.GetValue(FactoryProperty);
}
private static void PropertyChangedCallback(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var fe = dependencyObject as FrameworkElement;
if (fe != null)
{
fe.DataContext = GetFactory(dependencyObject).Create();
}
}
}
IViewModelFactory
public interface IViewModelFactory
{
object Create();
}
ViewModelFactory
public class MainViewModelFactory : ViewModelFactoryBase
{
protected override object CreateDesignTimeViewModel()
{
return new MainViewModel(new DesignTimeEventAggregator(), new DesignTimeLogger(), new ViewModelViewRepository());
}
protected override object CreateViewModel()
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
ViewModelFactoryBase Class
public abstract class ViewModelFactoryBase : IViewModelFactory
{
protected abstract object CreateDesignTimeViewModel();
protected abstract object CreateViewModel();
public object Create()
{
return Designer.IsInDesignTime() ? CreateDesignTimeViewModel() : CreateViewModel();
}
}
And in XAML, this is how I hookup ViewModel Locator to View:
<viewModelLocation:ViewModelLocator.Factory>
<viewModelFactories:MainViewModelFactory />
</viewModelLocation:ViewModelLocator.Factory>

Translating Structure Map into Autofac

I have recently puchased a very good book on MVVM - MVVM Survival Guide For Enterprise Architectures in Silverlight and WPF
Unfortunatly, one of the sections relating to IoC has a lot of code samples for StructureMap which is not available for Silverlight
Can anyone point me to a link that would help me translate Structure Map code to Autofac which is the injection tool I am looking at using
The code uses the factory mehod of creating classes and a bootstrapper
using Northwind.ViewModel;
using StructureMap;
namespace Northwind.UI.WPF
{
public class BootStrapper
{
public MainWindowViewModel MainWindowViewModel
{
get
{
return ObjectFactory
.GetInstance<MainWindowViewModel>();
}
}
public BootStrapper()
{
ObjectFactory.Initialize(
o => o.Scan(
a =>
{
a.WithDefaultConventions();
a.AssembliesFromApplicationBaseDirectory(
d => d.FullName
.StartsWith("Northwind"));
a.LookForRegistries();
}));
}
}
using StructureMap;
namespace Northwind.ViewModel
{
public class CustomerDetailsViewModelFactory
: ICustomerDetailsViewModelFactory
{
private readonly IContainer _container;
public CustomerDetailsViewModelFactory(
IContainer container)
{
_container = container;
}
public CustomerDetailsViewModel CreateInstance(
string customerID)
{
return _container
.With("customerID")
.EqualTo(customerID)
.GetInstance<CustomerDetailsViewModel>();
}
}
}
Paul
Autofac and StructureMap work differently, so you can't "translate" it one to one.
However, this is what it should look like to accomplish the same.
I've made some assumptions as not everything is there to test out your code.
public class BootStrapper
{
private readonly ILifetimeScope _container;
public BootStrapper()
{
var builder = new ContainerBuilder();
Assembly[] assemblies =
GetAssembliesFromApplicationBaseDirectory(
x => x.FullName.StartsWith("Northwind"));
builder.RegisterAssemblyTypes(assemblies)
.AsImplementedInterfaces();
// Module in Autofac = Registry in StructureMap
builder.RegisterAssemblyModules(assemblies);
Assembly viewModelAssembly =
typeof(MainWindowViewModel).Assembly;
builder.RegisterAssemblyTypes(viewModelAssembly);
_container = builder.Build();
}
private static Assembly[] GetAssembliesFromApplicationBaseDirectory(Func<AssemblyName, bool> condition)
{
string baseDirectoryPath =
AppDomain.CurrentDomain.BaseDirectory;
Func<string, bool> isAssembly =
file => string.Equals(
Path.GetExtension(file), ".dll", StringComparison.OrdinalIgnoreCase);
return Directory.GetFiles(baseDirectoryPath)
.Where(isAssembly)
.Where(f => condition(new AssemblyName(f)))
.Select(Assembly.LoadFrom)
.ToArray();
}
public MainWindowViewModel MainWindowViewModel
{
get
{
return _container.Resolve<MainWindowViewModel>();
}
}
}
public class CustomerDetailsViewModelFactory : ICustomerDetailsViewModelFactory
{
private readonly ILifetimeScope _container;
public CustomerDetailsViewModelFactory(ILifetimeScope container)
{
_container = container;
}
public CustomerDetailsViewModel CreateInstance(string customerID)
{
return _container.Resolve<CustomerDetailsViewModel>(
new NamedParameter("customerID", customerID));
}
}

MEF problem with import

I have problem with import shell-view-model to view-model class, I use MEF.
Shell-view-model :
namespace Spirit.ViewModels
{
using Caliburn.Micro;
using System.ComponentModel.Composition;
public interface IShellViewModel
{
void ShowLogOnView();
void ShowMessengerView();
}
[Export(typeof(IShellViewModel))]
public class ShellViewModel : Conductor<IScreen>, IShellViewModel
{
public ShellViewModel()
{
ShowLogOnView();
}
public void ShowLogOnView()
{
ActivateItem(new LogOnViewModel());
}
public void ShowMessengerView()
{
ActivateItem(new LogOnViewModel());
}
}
}
I need this class import in view-model class:
[Export]
public class LogOnViewModel : Screen, IDataErrorInfo
{
[Import]
private IShellViewModel _shellViewModel;
public void LogOn(string nick, string password)
{
IMessengerViewModel vm = IoC.Get<MessengerViewModel>();
_shellViewModel.ShowMessengerView();
}
}
Problem is after initialize is variable _shellViewModel null.
My bootstraper look like this:
public class MefBootStrapper : Bootstrapper<IShellViewModel>
{
}
MY SOLUTION:
I create interface assembly and refer this assembly in external service dll and also in wpf app.
In bootstraper I load this assembly with reflection:
var catalog =
new AggregateCatalog(
AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>());
catalog.Catalogs.Add(
new AssemblyCatalog(string.Format(
CultureInfo.InvariantCulture, "{0}{1}", System.IO.Directory.GetCurrentDirectory(), #"\Pokec_Toolkit.dll")));
_container = new CompositionContainer(catalog);
Than I create conductor class:
public interface IShellViewModel
{
void ShowLogOnView();
void ShowMessengerView();
}
[Export(typeof(IShellViewModel))]
public class ShellViewModel : Conductor<IScreen>, IShellViewModel
{
public ShellViewModel()
{
ShowLogOnView();
}
public void ShowLogOnView()
{
ActivateItem(IoC.Get<LogOnViewModel>());
}
public void ShowMessengerView()
{
ActivateItem(IoC.Get<MessengerViewModel>());
}
}
And in view-model I have this:
[Export]
public class LogOnViewModel : Screen, IDataErrorInfo, ILogOnViewModel
{
[Import]
private IShellViewModel _shellViewModel;
[Import]
private IPokecConnection _pokecConn;
//this method is bind on event click of button
public void LogOn(string nick, string password)
{
//SHOW NEW WIEW
_shellViewModel.ShowMessengerView();
}
}

Resources