Prism, Unity, and Default Type Registration in Modules

Technologies

  • C # 4.0
  • Prism 4 with unity for DI
  • WPF
  • MVVM

Introduction

There are two projects in my solution: MyApp.Shell and MyApp.ModuleFoo

MyApp.Shell Unity Bootstrapper

protected override IModuleCatalog CreateModuleCatalog()
{
    // Module assemblies are read from a directory.
    DirectoryModuleCatalog moduleCatalog = new DirectoryModuleCatalog();
    moduleCatalog.ModulePath = @".\Modules";
    return moduleCatalog;
}

The MyApp.ModuleFoo project contains a View and a View Model.

ViewModel

// Somehow, Unity sees this class and registers the type.
public class FooViewModel : ViewModelBaseClass
{
    public string FooText
    {
        get { return "Foo!"; }
    }
}

View

<Label Content={Binding FooText} />

Code view

// Unity automatically sees this as Constructor Injection, 
// which is exactly what I desire.
public FooView(FooViewModel viewModel)
{
    DataContext = viewModel;
    ...
}

Initializing MyApp.FooModule

Perhaps registering a FooView with a region manager inadvertently registers a FooViewModel with Unity?

public void Initialize()
{
    var regionManager = ServiceLocator.Current.GetInstance<IRegionManager>();
    regionManager.RegisterViewWithRegion("FooRegion", typeof(FooView));
}

The view displays "Foo!" Correctly.

Problems

  • How to tell Unity to register only one instance of FooViewModel?
  • Also (and I think ahead), how can I say unity so as not to register a FooViewModel?

Thanks for the help.

Edit:

Added initialization code MyApp.FooModule

Edit (decision):

, RegisterViewWithRegion . Prism, , , . , FooViewModel.

FooView. , "ViewModel-first". , - - , .

+3
1

// Somehow, Unity sees this class and registers the type. public class FooViewModel : ViewModelBaseClass     ...

, , Unity . , , .

( ), Unity , . , . .

:

.

Container.RegisterType<FooViewModel>(new ContainerControlledLifetimeManager());

, .

+4

All Articles