Register class with multiple interfaces for Dependency injection in Catel

588 views Asked by At

I'm using Catel 5.12.19 with an MVVM application

I have the following 2 interfaces:

  public interface ICustomerSearch
{
    public List<string> CustomerSearchFilterList { get; set; }
    public int SelectedFilter { get; set; }               
    public List<ICustomer> OnFindCustomer();
}

and

  public interface IService
{
}

I implement them as follow:

 public class CustomerControlService: IService, ICustomerSearch
    {        
        public IDBContext dbContext;    
    public List<string> CustomerSearchFilterList { get { return GetAvailableFilters(); } set {}
    public int SelectedFilter { get; set; }


    public CustomerControlService()
    {
        dbContext = new Model();            
    }
    public CustomerControlService(IDBContext context)
    {
        dbContext = context;            
    }

    public List<ICustomer> OnFindCustomer()
    {
        return new List<ICustomer>(dbContext.Customers);
    }

    private static List<string> GetAvailableFilters()
    {
        List<string> Result = new()
        {
            "Option 1",
            "Option 2"
        };
        return Result;
    }
    #endregion
}

In the app.xaml.cs I register this as follow:

ServiceLocator.Default.RegisterType<IService, CustomerControlService>();

In my model I inject it in the constructor like:

public CustomerControlViewModel(IService customerControl/* dependency injection here */) 
    {
        customersController = (CustomerControlService)ServiceLocator.Default.ResolveType<IService>();                   
    }

But then I can't do:

 public List<string> CustomerSearchFilterList = customersController.CustomerSearchFilterList;

Can I accomplish this and how?

Jeroen

1

There are 1 answers

1
ChrisBD On BEST ANSWER

IService interface is blank, therefore any code using IService can perform no actions with it.

CustomerSearchFilterList is defined as belonging to ICustomerSearch interface.

Thus for dependency injection you should be using concrete classes based upon ICustomerSearch instead of IService.

You can combine interfaces to form more complex ones e.g.

public interface IComplexInterface : ICustomerSearch, IService
{
}

Then you could inject concrete classes based upon IComplexInterface and call interface methods or properties from both ICustomerSearch and IService