Question

I am in the process of learning Caliburn.Micro and Autofac at the same time. I am writing a simple app so I can teach myself how to properly use these two technologies.

Each time I think I am getting somewhere, I always get tripped up on how to initialize my data for my root viewmodel. This viewmodel needs to have a list of "category" viewmodels injected. This list of "category" viewmodels will be loaded during app initialization.

So, how do I register my root "Navigator" viewmodel with autofac and inform autofac that the viewmodel needs to have data injected when a new instance is created?

Without caliburn and autofac I would simply create my own startup method, load my data, and inject it into my viewmodel. With caliburn, I am attempting to override the configure method in the bootstrapper as this is where I should register my classes with the ioc container.

My root viewmodel:

public class NavigatorViewModel : Conductor<IScreen>.Collection.OneActive
{
    public NavigatorViewModel(IEnumerable<CategoryViewModel> categories)
    {
        AddCategories(categories);
    }

    public void AddCategories(IEnumerable<CategoryViewModel> categories)
    {
        foreach (var category in categories)
        {
            if (Items.Contains(category))
                continue;
            Items.Add(category);
        }
        SetActiveItem();
    }

    private void SetActiveItem()
    {
        if (Items.Count < 1)
            return;
        ActiveItem = Items[0];
    }
}

Here is how I am registering the viewModels with Autofac:

protected override void Configure()
{
    var builder = new ContainerBuilder();

    builder.RegisterType<CategoryViewModel>().AsSelf();
    builder.RegisterType<NavigatorViewModel>().AsSelf();
    ...
    container = builder.Build();
}

When registering my NavigatorViewModel how do I tell autofac that it needs to have the list of CategoryViewModels injected as well?

I am guessing that I will load my data within the caliburn bootstrapper, but I am just unsure how to hook it all up at this point.

Was it helpful?

Solution

This looks like a question about AutoFac rather than MVVM or Caliburn.Micro, anyway as far as i know AutoFac supports Auto-Wiring for sequences (IEnumberable) automatically so it should fill up the list all by it self when it tries to resolve your Navigator, but if you need to provide custom work for data loading you can do it like this:

builder.RegisterType<NavigatorViewModel>()
.AsSelf()
.WithParameter(
(p, c) => true, 
(p, c) => new[] 
{ 
// Load your CategoryViewModels here or any other data that you would like
});

you can check AutoFac documentation on the WithParameter method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top