Constructor dependency injection in constructor

I have a service that uses ApplicationContext. So I want to use dependency injection so that the application gives me context. So I put in the design

Private _context;

// Constructor
public Service(ApplicationContext context) {
    _context = context
}

The problem is, when I initialize this service, do I have to pass context to it so that there really is no dependency injection?

Is there a way to get the context that is entered without putting it in the constructor options?

****** EDIT *****

I'm sorry that I did not give enough information for the first time. Let me try to explain it better. I have a service that I’ll call right now. It reads the header variables in the query database and returns xml by their values. I create an instance in every other controller method, because they can have different values ​​for the header variables. I would like the context to inject into the service instead of the controller, so I can say the following:

Service service = new Service(Request);

Instead of this:

Service service = new Service(Request, Context);

The reason that the service does all the work with the context, the dispatcher does not need to know anything about it. The code that I have will work, but it would be great if I could work as I explained.

[FromServices] . . , . . .

?

, .

+4
2

. DI . ApplicationContext Startup.cs.

, , DI ApplicationContext .

, , , @Oleg.

+1

, , , ApplicationContext . HttpContext, [FromServices] . . .

[Route("api/[controller]")]
public class MyController : Controller
{
    [HttpGet]
    public async IEnumerable<object> Get([FromServices] ApplicationContext context,
                                         MyType myMainParam)
    {
        ...
    }
}

RC1 [FromServices] , RC2 (. ). .

+2

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


All Articles