在 Catel 中使用多个接口注册 class 以进行依赖注入

Register class with multiple interfaces for Dependency injection in Catel

我将 Catel 5.12.19 与 MVVM 应用程序一起使用

我有以下2个接口:

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

  public interface IService
{
}

我按如下方式实现它们:

 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
}

在 app.xaml.cs 中,我注册如下:

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

在我的模型中,我将其注入到构造函数中,例如:

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

但是我做不到:

 public List<string> CustomerSearchFilterList = customersController.CustomerSearchFilterList;

我能做到吗?如何做到?

杰伦

IService 界面是空白的,因此任何使用 IService 的代码都不能对其执行任何操作。

CustomerSearchFilterList 定义为属于 ICustomerSearch 接口。

因此,对于依赖注入,您应该使用基于 ICustomerSearch 的具体 类 而不是 IService

您可以组合接口以形成更复杂的接口,例如

public interface IComplexInterface : ICustomerSearch, IService
{
}

然后你可以根据 IComplexInterface 注入具体的 类 并从 ICustomerSearchIService

调用接口方法或属性