I am kind of new to Unity and DI terminology, hence trying to understand how does it work. I have following code which implements DI using Unity container.
public class DashboardService: IDashboardService
{
private readonly IRepository<USERROLE> repoUserRole;
private readonly IRepository<INSTITUTION> repoInstitution;
public DashboardService(
IRepository<USERROLE> repoUserRole, IRepository<INSTITUTION> repoInstitution)
{
this.repoUserRole = repoUserRole;
this.repoInstitution = repoInstitution;
}
public List<USERROLE> GET(List<string> Id)
{
// Use repoUserRole object to get data from database
}
}
This service is being called by the controller:
public class DashboardController : ApiController
{
private readonly IDashboardService dashboardService;
public DashboardController(IDashboardService dashboardService)
{
this.dashboardService = dashboardService;
this.mapper = mapper;
}
//Action method which uses dashboardService object
}
Here is the Unity configuration:
var container = new UnityContainer();
container.RegisterType(typeof(IDashboardService), typeof(DashboardService))
.RegisterType(typeof(IRepository<>), typeof(Repository<>));
return container;
Questions:
- As of now, my code works fine, but if I comment out the
DashboardServiceconstructor, I am getting the null repository objects. - I am resolving the dependencies in
Unityfor repository interfaces, so why I am getting null there? - Is there any way to pass the repository dependancy without using the constructor pattern?