如何回调调用类以访问变量

时间:2019-08-30 12:05:10

标签: c# dependency-injection

我正在使用构造函数依赖项注入。在我的主类(分析器类)中,我将所有其他类作为服务注入。然后,Analyzer类将在注入的类(peopleService类)中调用一个方法。该方法返回人员列表。但是我需要将一些其他信息存储回调用方类(Analyzer类)中。我已经在Analyzer类中创建了一个静态IList来存储它,但是我不知道谁要调用Analyzer类的IList来存储来自peopleService类中的方法的数据。我应该在peopleSerivce类中创建Analyzer类的实例,还是有适当的方法呢?请以正确的方式提出建议。

//---- analyzer class ----
private static readonly List<string> MissingItemsInMapping = new List<string>();

public IList<string> MissingItemsInMappingsList => MissingItemsInMapping;
private readonly IPeopleService _peopleService;

//constructor
public Analyzer(IPeopleService peopleService)

{
   _peopleService = peopleService;
}

//calling people service method
var people = _peopleService.GetPeopleForEvent(category, date);

//---- People class ----
public IList<People> GetPeopleForEvent(string category, DateTime date)
{
  var ppl = new List<People>();
  If()
  {
    //some logic

    return ppl;
  }
  else
  {
    // This is where I need to access and send back data into MissingItemsInMapping list of Analayzer class's. It will be later used to send some mail
    // -- How to do this? --
    return new List<People>(); 
  }
}

1 个答案:

答案 0 :(得分:0)

您的原始代码从不使用调用服务的方法。您正在使用一个字段。如果这是预期的用法,那么这里是一个可能的解决方案。

//---- analyzer class ----
private static List<string> MissingItemsInMapping = new List<string>();

public IList<string> MissingItemsInMappingsList => MissingItemsInMapping;
private readonly IPeopleService _peopleService;

//constructor
public Analyzer(IPeopleService peopleService)

{
   _peopleService = peopleService;
}

//calling people service method
var people = _peopleService.GetPeopleForEvent(category, date, MissingItemsInMapping);

//---- People class ----
public IList<People> GetPeopleForEvent(string category, DateTime date, List<string> information)
{
  var ppl = new List<People>();
  If()
  {
    //some logic

    return ppl;
  }
  else
  {
    // You have access to MissingItemsInMapping here, use .Add, or whatever suits you
    // to add/modify the list.
    return information;
  }
}