Dependency injection when calling a controller from another controller

I have one ASP.NET 5.0 (vnext) project in which I implement both Web Api and the Mvc frontend. I want my Mvc controller to call the Web Api controller, which works fine. I built the api using the example http://www.asp.net/vnext/overview/aspnet-vnext/create-a-web-api-with-mvc-6 and it works fine. The front end of Mvc can successfully invoke the WebApi controller, but ITodoRepository is not provided by the dependency injection infrastructure when I create an instance from the Mvc controller.

public class Startup
{
    public void Configure(IApplicationBuilder app, ILoggerFactory logFactory)
    {
        ...
        app.UseServices(services =>
        {
            services.AddSingleton<ITodoRepository, TodoRepository>();
        });
        ...

[Route("api/[controller]")]
public class TodoController : Controller
{
    /* The ITodoRepository gets created and injected, but only when the class is activated by Mvc */
    TodoController(ITodoRepository repository)
    {
        _repository = repository;
    }

    [HttpGet]
    public IEnumerable<TodoItem> Get()
    {
        return _repository.AllItems;
    }
    ...

public class HomeController : Controller
{
    public IActionResult Index()
    {
        var tc = new TodoController(/* have to create my own ITodoRepository here */);
        return View(tc.Get());
    }
    ...

ITodoRepository HomeController [], TodoController, . .

TodoController, DI ?

+4
2

, , .

:

  • (.. MVC)

, -, , , , , -.

public class HomeController : Controller {
    public HomeController(IMyAppBusinessLogic bll) { ... }
}

public class WebApiController : Controller {
    public WebApiController(IMyAppBusinessLogic bll) { ... }
}

public class MyAppBusinessLogic : IMyAppBusinessLogic {
    public MyAppBusinessLogic(ITodoRepository repository) { ... }
}
+5

, app.UseServices, -. - , webapi MVC, .

. , DI , - (OWIN vNext), SimpleInjector

public static void UseInjector(this IAppBuilder app, Container container)
{
    // Create an OWIN middleware to create an execution context scope
    app.Use(async (context, next) =>
    {
        using (var scope = container.BeginExecutionContextScope())
        {
            await next.Invoke();
        }
    });            
}
0

Source: https://habr.com/ru/post/1570802/


All Articles