Alexey Titov
Alexey Titov

Reputation: 353

WPF Prism.Unity - how to construct a ViewModel using named dependency injection

Using Prism 7.1, I can register two named dependencies:

containerRegistry.Register<ICustomersService, CustomersFakeService>("One");
containerRegistry.Register<ICustomersService, CustomersFakeService>("Two");

Now - how can I use any of them in ViewModel constructor?

public CustomersViewModel(ICustomersService customersService, EventAggregator eventAggregator)

throws an exception:

Resolution of the dependency failed, type = 'WPFPrismDI.ViewModels.CustomersViewModel', name = '(none)'. Exception occurred while: while resolving. Exception is: InvalidOperationException - The current type, WPFPrismDI.Services.ICustomersService, is an interface and cannot be constructed. Are you missing a type mapping? ----------------------------------------------- At the time of the exception, the container was: Resolving WPFPrismDI.ViewModels.CustomersViewModel,(none) Resolving parameter 'customersService' of constructor WPFPrismDI.ViewModels.CustomersViewModel(WPFPrismDI.Services.ICustomersService customersService, Prism.Events.EventAggregator eventAggregator) Resolving WPFPrismDI.Services.ICustomersService,(none)

My implementation of the service:

public interface ICustomersService
{
    ObservableCollection<CustomerModel> CustomerGetAll();
}

public class CustomersDBService : ICustomersService
{
    public ObservableCollection<CustomerModel> CustomerGetAll()
    {
        ObservableCollection<CustomerModel> returnValue = new ObservableCollection<CustomerModel>();

        returnValue.Add(new CustomerModel() { NameFirst = "DB", });

        return returnValue;
    }
}

Upvotes: 1

Views: 795

Answers (1)

Haukinger
Haukinger

Reputation: 10863

Now - how can I use any of them in CustomersViewModel constructor?

By injecting all of them:

public CustomersViewModel(ICustomersService[] customersServices, IEventAggregator eventAggregator)

Upvotes: 1

Related Questions