Is it possible to get current Unity container inside controller

后端 未结 4 2034
难免孤独
难免孤独 2021-01-02 11:11

I registered unity container like this:

    var container = new UnityContainer();

    container.RegisterType(new Containe         


        
4条回答
  •  情话喂你
    2021-01-02 11:55

    Although it is possible to that, it's best that you avoid it.

    It's best that you take any dependencies the controller needs via constructor parameters. This way, the class (controller) makes it clear what are the dependencies required for it to run.

    If configured correctly, the container will provide those dependencies and their dependencies (if any), and so on.

    The usage of an IoC container should typically be restricted to only one place inside an application (called the composition root). Any extra reference/call to the container is susceptible to lead to the Service Locator anti-pattern. See the linked article for reasons why such an approach may be bad.

提交回复
热议问题