2016-08-21 37 views
1

私は第三者から引っ張るためにクラス内に2つのリストを設定する関数を持っています。
サードパーティに行くには時間がかかるので、私は1つの機能に入れました。このページでは1回だけしなければなりません。 - それぞれのリストを返す1プロパティが既に設定されている場合、関数が呼び出されないようにするにはどうすればよいですか?

public class MyClass 
{ 
    public IEnumerable<dynamic> ListOne { get; set; } 
    public IEnumerable<dynamic> ListTwo { get; set; } 
} 

これは&戻っリスト

public MyClass GetLists() 
    { 
      //Here I have the code that connects to the third party etc 
      //Here set the items.. from the third party 
      MyClass _MyClass = new MyClass(); 
      _MyClass.ListOne = ThirdParty.ListOne; 
      _MyClass.ListTwo = ThirdParty.ListTwo; 
      return (_MyClass); 
     }; 
    } 

だから、今、私のウェブAPIで、私は2つの機能を持っているを設定し、私の機能は次のとおりです。 は、これは私のクラスです。

[Route("ListOne")] 
    public IHttpActionResult GetListOne() 
     { 
     IEnumerable<dynamic> ListOne = GetLists().ListOne; 
     return Json(ListOne); 
     } 

    [Route("ListTwo")] 
    public IHttpActionResult GetListTwo() 
     { 
     IEnumerable<dynamic> ListTwo = GetLists().ListTwo; 
     return Json(ListTwo); 
     } 

私の問題は、私はWEBAPI getListoneまたはgetListTwo呼び出すたびに、機能を再度実行し、第三者を呼び出すことです。どうすればこれを防ぐことができますか?

ありがとうございました!

答えて

1

データ検索ロジックをプロパティに配置し、データを遅延ロードします。つまり、プロパティが初めて呼び出されたときに読み込みます。

private IEnumerable<dynamic> _listOne; 
public IEnumerable<dynamic> ListOne { 
    get { 
     if (_listOne == null) { 
      // Retrieve the data here. Of course you can just call a method of a 
      // more complex logic that you have implemented somewhere else here. 
      _listOne = ThirdParty.ListOne ?? Enumerable.Empty<dynamic>(); 
     } 
     return _listOne; 
    } 
} 

?? Enumerable.Empty<T>() nullが確実に返されないようにします。代わりに、空の列挙が返されます。

参照:?? Operator (C# Reference)
              Enumerable.Empty Method()

Lazy<T> Classを見てください。

+0

ありがとうございます。私は2つの質問がある)私は、私はプロパティ自体に多くのコードを置くはずではないと思った? (それは第三者に接続するコードがかなりあります)b)ThirdParty.listOneがnullを返すと、それは再び実行されますか? – shw

+0

メインデータ検索ロジックを別の場所に配置し、このロジックをプロパティから呼び出すことができます。 –

+0

私はそれを行います。ありがとう – shw

関連する問題