結論:普通にDIできる。
Service → Model → Repository といった構成の場合は下記のようにDIの連鎖が作られていれば、ControllerにDIされる際に、下層にもDIが行われる。
[Startup.cs]
// DIの登録
services.AddTransient<IService, SampleService>();
services.AddTransient<IModel, SampleModel>();
services.AddTransient<IRepository, SampleRepository>();
[DIController.cs]
public class DIController : Controller
{
/// <summary>
/// Controller InjectionでDIされるサービス
/// </summary>
private readonly IService service;
/// <summary>
/// コンストラクタ
/// </summary>
public DIController(IService service)
{
this.service = service;
}
/// <summary>
/// DIテスト
/// </summary>
[HttpGet]
public IActionResult Index()
{
service.Doing();
return RedirectToAction("Index", "Home");
}
}
[SampleService.cs]
public class SampleService : IService
{
private readonly IModel model;
public SampleService(IModel model)
{
this.model = model;
}
public void Doing()
{
model.Store();
}
}
[SampleModel.cs]
public class SampleModel : IModel
{
private readonly IRepository repository;
public SampleModel(IRepository repository)
{
this.repository = repository;
}
public void Store()
{
repository.Insert();
}
}
[SampleRepository.cs]
public class SampleRepository : IRepository
{
public void Insert()
{
Console.WriteLine("INSERT INTO DB");
}
}