Untitled

ASP.NET Dependency Injection
 avatar
unknown
csharp
2 years ago
2.6 kB
5
Indexable
builder.services.AddScoped<ICompanyService, CompanyService>()
	.AddScoped<ICompanyRepository, CompanyRepository>()
	
// Adding BC/Service to the DI container as Scoped  means it will automatically be injected into any controller that takes an ICompanyService as a contructor argument

// Also registering the repository class as Scoped and having the BC/Service take an ICompanyRepository means that when the DI container injects the ICompanyService instance into the controller constructor, it sees that the BC needs an ICompanyRepository as a constructor argument, and since that type is registered in the container, it is in turn injected into the ICompanyService instance that is injected into the controller.

public class CompanyController : Controller
{
    private ICompanyService _companyService;
    
    public CompanyController(ICompanyService companyService) 
    {
        // When the controller is created in response to a http request, the DI container sees that it
        // wants an ICompanyService as an argument, which is registered in the DI container, so it passes
        // a request scoped instance of the assigned concrete implementation into the constructor.
        
        // However, it also sees that upon instantiating a CompanyService (concrete implementation of ICompanyService),
        // it sees that the CompanyService in turn also requires a constructor argument.
        // Since we have also registered what the CompanyService wants in its constructor, the DI container then passes
        // a request scoped instance of CompanyRepository (concrete implementation of ICompanyRepository that we specified)
        _companyService = companyService;
    }
    
    [HttpGet]
    public IActionResult GetAllCompanies()
    {
        // Cool validation logic stuff here
        return _companyService.GetAllCompanies();
    }
}

public interface ICompanyService
{
    IEnumerable<Company> GetAllCompanies();
}

public class CompanyService : ICompanyService
{
    private ICompanyRepository _companyRepository;
    
    public CompanyBC(ICompanyRepository companyRepository)
    {
        _companyRepository = companyRepository;
    }
    
    public IEnumerable<Company> GetAllCompanies()
    {
        var companies = _companyRepository.GetAllCompanies();
        
        // Cool business logic and mapping stuff here
        
        return companies;
    }
}

public interface ICompanyRepository
{
    IEnumerable<Company> GetAllCompanies();
}

public class CompanyRepository : ICompanyRepository
{
    public IEnumerable<Company> GetAllCompanies()
    {
        // Cool DB access stuff here
    }
}
	
Editor is loading...