adam78
adam78

Reputation: 10068

c# - Object Oriented Programming Factory Method Contructor

In C# and constructor dependency injection what is the difference between the first two constructors. Specifically what does the :this in the first constructor signify. Is it just shorthand for the second constructor or something else?

    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;
    }

Upvotes: 0

Views: 72

Answers (1)

Igal23
Igal23

Reputation: 122

You should not create the first 2 constructors because the dependency injection container will handle how to create the repository and the service.

The this keyword is used in scenarios like

Public Person(string name){}

public Person(string name, string lastname) :this(name)
{ 
    // calls first constructor and then..
    // do something with lastname
} 

Upvotes: 1

Related Questions