pilsdumps
pilsdumps

Reputation: 617

Prism and Unity - prevent auto creation of type

I'm creating a WPF app using Prism and Unity as the container. A couple of times I've come unstuck with the order of registering types whereby a type (ViewModel into View constructor) has been auto created by Unity when I've not registered it. Then I've tried to register the type using ContainerControlledLifetimeManager() and thought I'd created a singleton. However the auto creation has meant multiple instances of the view model.

Besides the obvious solution of not being a muppet and not doing the above, is there a way to prevent Unity auto creating unregistered types and perhaps throwing an exception instead?

Upvotes: 0

Views: 585

Answers (1)

Aaron McIver
Aaron McIver

Reputation: 24713

Define an interface for each of your ViewModels and then register them accordingly.

public interface IViewModel
{
     List<IUser> Users { get; }
}

public class ViewModel : IViewModel
{
     List<IUser> Users { get; }
}

Container.RegisterType<IViewModel, ViewModel>();

In your constructor make sure that the interface type is being injected, not the concrete type as Unity will certainly construct an instance of a concrete type since it is resolvable; whereas an interface can have N implementations.

In addition, your code should be constructed in that the data that needs to exist across the application should come form a service, not the ViewModel. Making your ViewModel a singleton should not be your approach, proxy the data through a service. this way your ViewModel can be constructed/destroyed at will, the data you want persisted exists elsewhere.

Container.RegisterType<IService, Service>(new ContainerControlledLifetimeManager());
Container.RegisterType<IViewModel, ViewModel>();

...

public List<IUser> Users
{
     get { return Container.Resolve<IService>().GetUsers(); }
}

Upvotes: 1

Related Questions