Custom bootstrapper from Caliburn.Micro.Bootstrapper, what is Bootstrapper<IContract> for? - wpf

I have derived a custom bootstrapper from Caliburn.Micro.Bootstrapper, I notice it can take a generic type parameter - what is this for?
public class SimpleInjectorBootstrapper : Caliburn.Micro.Bootstrapper
{
private Container container;
public SimpleInjectorBootstrapper()
{
}
protected override void Configure()
{
this.container = new Container();
this.container.Register<IWindowManager, WindowManager>();
this.container.Register<IEventAggregator, EventAggregator>();
this.container.Register<IAppViewModel, AppViewModel>();
}
protected override object GetInstance(Type serviceType, string key)
{
return this.container.GetInstance(serviceType);
}
protected override IEnumerable<object> GetAllInstances(Type serviceType)
{
return this.container.GetAllInstances(serviceType);
}
protected override void OnStartup(object sender, System.Windows.StartupEventArgs e)
{
base.OnStartup(sender, e);
var appViewModel = this.container.GetInstance<IAppViewModel>();
var windowManager = this.container.GetInstance<IWindowManager>();
windowManager.ShowWindow(appViewModel);
}
}

It's a view model type to use as your starting view model. Caliburn.Micro will resolve the type from the IoC container, and in WPF use the WindowManager to display the root view. Bascially what you're doing in your OnStartup override.

Related

Change the View on button Click in WPF MVVM Pattern

I have 3 buttons on one usercontrol (usercontrol1.xaml) in the Window . Now on-click of button 1 ,I want to switch the view to another usercontrol (usercontrol2.xaml), which again have 3 buttons and so on.
How to implement in MVVM Pattern in WPF?
Be aware that im using caliburn micro for this example
private IEventAggregator _eventAggregator => IoC.Get<IEventAggregator>(key: nameof(EventAggregator));
private IWindowManager _windowManager => IoC.Get<IWindowManager>(key: nameof(WindowManager));
public ShellViewModel(IEventAggregator eventAggregator)
{
_eventAggregator.Subscribe(this);
}
public string _firstName;
// public ShellViewModel page = new ShellViewModel();
public string FirstName
{
get {
return _firstName;
}
set
{
_firstName = value;
NotifyOfPropertyChange(() => FirstName);
}
}
public ICommand ConvertTextCommand
{
get { return new DelegateCommand(ConvertText); }
}
void ConvertText()
{
//string url = "https://www.google.com/";
string url = FirstName;
string result;
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
result = content.ReadAsStringAsync().Result;
}
}
}
//(MainWindow)Application.Current.MainWindow).txtForm1TextBox.Text = "Some text";
//Application.Current.Resources.Add("PageSource", result);
// NavigationService.NavigateToViewModel<SecondViewModel>("Hello");
_windowManager.ShowWindow(new PageSourceViewModel(_eventAggregator), null);
_eventAggregator.PublishOnUIThread(result);
}
You can check caliburn micro and see that you can just create a new view model in a window manager instance
here is also 2 links to 2 tutorials that helped me solve this issue for MVVM
https://www.youtube.com/watch?v=laPFq3Fhs8k
https://www.youtube.com/watch?v=9kGcE9thwNw&list=LLy8ROdSzpPJnikdZQ1XPZkQ&index=30&t=0s
the first tutorial will help you to get a general idea. The second will help you with events and you can look back to my code and see how i handled a new window instance.
You can also call the same view model for a new instance of the same window like you said in the question
You will also need to make a boostrapper class. For my example i did it like this.
public class Bootstrapper : BootstrapperBase
{
private readonly SimpleContainer _container =
new SimpleContainer();
public Bootstrapper()
{
Initialize();
}
protected override void Configure()
{
_container.Instance<IWindowManager>(new WindowManager());
_container.Singleton<IEventAggregator, EventAggregator>();
_container.PerRequest<ShellViewModel>();
}
protected override void OnStartup(object sender, StartupEventArgs e)
{
_container.Instance<SimpleContainer>(_container);
_container.Singleton<IWindowManager, WindowManager>(key: nameof(WindowManager))
.Singleton<IEventAggregator, EventAggregator>(key: nameof(EventAggregator));
DisplayRootViewFor<ShellViewModel>();
}
protected override object GetInstance(Type service, string key)
{
return _container.GetInstance(service, key);
}
protected override IEnumerable<object> GetAllInstances(Type service)
{
return _container.GetAllInstances(service);
}
protected override void BuildUp(object instance)
{
_container.BuildUp(instance);
}
}

Open new window on click in WPF, Ninject and Caliburn.Micro

I'm trying to set up a WPF app to call the new window on a menu click with the data provider interface injected into the new viewmodel.
Followed many tutorials and created the Bootstrapper for Caliburn, a service locator and module for ninject. So far the main view doesn't need the IDataProvider but I'd like to open a new window on click event.
The Bootstrapper:
public class Bootstrapper : BootstrapperBase
{
public Bootstrapper()
{
Initialize();
}
protected override void OnStartup(object sender, StartupEventArgs e)
{
DisplayRootViewFor<MainScreenViewModel>();
}
}
The Service Locator and Module:
public class ServiceLocator
{
private readonly IKernel _kernel;
public ServiceLocator()
{
_kernel = new StandardKernel(new ServiceModule());
}
public MainScreenViewModel MainScreenViewModel => _kernel.Get<MainScreenViewModel>();
public NewLayoutViewModel NewLayoutViewModel => _kernel.Get<NewLayoutViewModel>();
}
public class ServiceModule : NinjectModule
{
public override void Load()
{
Bind<ISqlite>().To<Sqlite>();
Bind<IDataProvider>().To<DataProvider>();
}
}
And this is where I got stuck:
public class MainScreenViewModel : Conductor<object>
{
private IWindowManager _windowManager;
public MainScreenViewModel()
{
_windowManager = new WindowManager();
}
public void NewLayout()
{
_windowManager.ShowWindow(new NewLayoutViewModel());
}
}
since the NewLayoutViewModel requires the IDataProvider.
Not sure, what am I missing, but in my understanding Ninject should take care of this di for NewLayoutViewModel.
Found a good solution from Tim Corey on YouTube.
Basically the answer is, if you not insist Ninjet, use Caliburn.Micro's build-in DI solution "SimpleContainer".

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>

WPF, Prism, Unitybootstrapper, and Enterprise Library Logging setup throwing LogWriter exception

I'm just trying to get up off the ground and get used to working with Prism, in my bootstrapper I have:
public class Bootstrapper : UnityBootstrapper
{
private readonly EnterpriseLibraryLoggerAdapter _logger = new EnterpriseLibraryLoggerAdapter();
protected override void InitializeShell()
{
base.InitializeShell();
Application.Current.MainWindow = (Shell)this.Shell;
Application.Current.MainWindow.Show();
}
protected override DependencyObject CreateShell()
{
return this.Container.Resolve<Shell>();
}
protected override ILoggerFacade CreateLogger()
{
return _logger;
}
for my App OnStartup:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Bootstrapper bootstrapper = new Bootstrapper();
bootstrapper.Run();
}
}
And the logging adapter
public class EnterpriseLibraryLoggerAdapter : ILoggerFacade
{
#region ILoggerFacade Members
public void Log(string message, Category category, Priority priority)
{
Logger.Write(message, category.ToString(), (int)priority); // <--Blows up here
}
#endregion
}
When the bootstrapper Runs, it hits the Logger.Write and throws an exception:
The type LogWriter does not have an accessible constructor.
I'm following from the StockTraderRI sample app. Am I missing a registration somewhere?
moved the configuration to my bootstrapper constructor and things seem to be working
var builder = new ConfigurationSourceBuilder();
builder.ConfigureLogging()
.WithOptions
.DoNotRevertImpersonation()
.LogToCategoryNamed("Debug")
.SendTo.FlatFile("Basic Log File")
.FormatWith(new FormatterBuilder()
.TextFormatterNamed("Text Formatter")
.UsingTemplate(
"Timestamp: {timestamp}{newline}Message: {message}{newline}Category: {category}{newline}"))
.ToFile("core.log")
.SendTo.RollingFile("Rolling Log files")
.RollAfterSize(1024)
.ToFile("RollingTest.log")
.LogToCategoryNamed("General")
.WithOptions.SetAsDefaultCategory()
.SendTo.SharedListenerNamed("Basic Log File");
var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

MEF problem with import

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)

Resources