2017-11-03 14 views
0

C#とコンストラクタ依存性注入では、最初の2つのコンストラクタの違いは何ですか?特に、最初のコンストラクタの:thisは何を表していますか? 2番目のコンストラクタや他の何かの省略形ですか?c# - オブジェクト指向プログラミングファクトリメソッドコンストラクタ

private readonly IRepositoryOne _repositoryOne; 
    private readonly IRepositoryTwo _repositoryTwo; 
    private readonly IService _service; 
    private readonly ApplicationDbContext _context; 

    public MyContructor() 
     : this(new RepositoryOne(new ApplicationDbContext()), 
       new RepositoryTwo(new ApplicationDbContext()) 
       new Service()) 
    { 

    } 

    public MyContructor() 
    { 
     _context = new ApplicationDbContext(); 
     _repositoryOne = new RepositoryOne(_context); 
     _repositoryTwo = new RepositoryTwo(_context); 
     _service = new Service(); 
    } 


    public MyContructor(IRepositoryOne repositoryOne, 
         IRepositoryTwo repositoryTwo, 
         IService service) 
    { 
     _repositoryOne = repositoryOne; 
     _repositoryTwo = repositoryTwo; 
     _service = service; 
    } 
+0

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-constructors –

+0

のようなシナリオで使用されていますhttps://stackoverflow.com/questions/1814953/c-sharp-constructor-chaining-how-to-do-it – Nkosi

+0

@ L.Guthardt最初の人は3番目の人を呼び出します。 – Nkosi

答えて

1

依存関係注入コンテナがリポジトリとサービスの作成方法を処理するため、最初の2つのコンストラクタは作成しないでください。

thisキーワードは

Public Person(string name){} 

public Person(string name, string lastname) :this(name) 
{ 
    // calls first constructor and then.. 
    // do something with lastname 
} 
関連する問題