I am creating a new web api project. In this i am using two more class library projects apart from web api project Like this:
MyBlog.API (Web API project)
MyBlog.Services (Class library)- Contains additional business logic
MyBlog.Repositories (Class library) - contains all database related operations
In API project i have added the reference of Services project and in Services project i have added reference of Repositories project so API will call services and services will call repositories as this:
API > Services > Repositories
I don't want to call repositories directly form my api controllers they will be called through services. So i am not adding repository project reference in api project.
Now i am implementing unity.webapi dependency injection in my api project. Following is the code for implementing DI:
Repositories code:
namespace MyBlogs.Repositories
{
public interface ITestRepository
{
string Get();
}
}
namespace MyBlogs.Repositories
{
public class TestRepository:ITestRepository
{
public string Get()
{
return "test";
}
}
}
Services code with DI implementation:
namespace MyBlogs.Services
{
public interface ITestService
{
string Get();
}
}
namespace MyBlogs.Services
{
public class TestService : ITestService
{
private ITestRepository testRepository;
public TestService(ITestRepository testRepositoryParam)
{
this.testRepository = testRepositoryParam;
}
public string Get()
{
return this.testRepository.Get();
}
}
}
Controller code:
public class ValuesController : ApiController
{
private ITestService testService;
public ValuesController(ITestService testServiceParam)
{
this.testService = testServiceParam;
}
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { this.testService.Get() };
}
}
and finally unityconfig file:
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType<ITestService, TestService>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
Now i am facing the issue here, as i have not added repository project reference in api project where i have this unityconfig file so how can i register ITestRepository and TestRepository in unity similart to ITestService and TestService?? Is there any way i could register my repository project's dependencies somewhere else without adding the project reference?? or if i will try to add unity in services project then how will it gets registered??
I have registered unityConfig in global.asax of web api project:
protected void Application_Start()
{
UnityConfig.RegisterComponents();
}