@
@
@insighter2021-08-18 15:45:36
C++ / C#
@insighter, 2021-08-18 15:45:36

How to organize such routing?

I want to organize routing for example such a request:
www.myname.ru/services/{dbId}/api/data/get?id=...

It is clear that after api there is a bunch of controllers and it would be necessary to implement centralized processing of the "dbId" parameter. In fact, this is the identifier of the data scheme with which the controllers will work. Different companies can work with the API, and each company stores data in its own schema.

[ApiController]
    [Route("services/{dbId}/api/[controller]")]
    public class DataController : ControllerBase
    {
        protected MyDbContext Dbx { get; private set; }

        public DataController(MyDbContext dbx)
        {
            Dbx = dbx;
      // здесь ничего не известно о структуре запроса, а хочется инициализировать dbx
        }


        [HttpGet]
  [Route("get")]
        public async Task<IActionResult> Get([FromRoute]string dbId, string id)
        {
    ...


I understand how to get the dbId in the controller methods, everything works. But how can I get the dbId in the constructor to write it to the DbContext.

Maybe someone will give general advice on how best to organize an API that works in a similar context isolated from each other (/services/{dbId}/...).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-08-19
@sarapinit

In my opinion, this is the case when you need to abandon dependency injection and steer the creation and lifetime of the DbContext yourself. You can create a factory that duplicates the code to create a context depending on the dbId and have it get a constructor where needed. But here it will be necessary to release the context by hand.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question