Is it a preferred approach to inject IUnityContainer itself as an argument inside ASP.NET MVC Controller Constructor

半腔热情 提交于 2019-12-11 12:37:05

问题


I am using Unity.Mvc4 in asp.net MVC 4 and have built-in Bootstrapper file to register all types like below.

   public static class Bootstrapper
        {
            public static IUnityContainer Initialise()
            {
                var container = BuildUnityContainer();

                DependencyResolver.SetResolver(new UnityDependencyResolver(container));

                return container;
            }
    -----------------------
    ------------------------

In my Controller constructor, I am injecting IUnityContainer itself for calling Resolve() on demand, like below

 private IQuestionBusinessLogic _qstnBL;

 public MyController(IUnityContainer unityContainer)
            : base(unityContainer)

        {   

                     qstnBL = _unityContainer.Resolve<IQuestionBusinessLogic>();
    }

Queries are

  1. Is there any performance burden by injecting IUnityContainer unityContainer itself?
  2. Is there any other way to call Resolve() than access the IUnityContainer unityContainer this way?
  3. Make a call to Resolve() it self has any performance burden?

回答1:


That's a really bad approach to architecture your classes. Instead of making explicit dependencies between services, you spoil your classes with dependencies to specific IoC framework.

The IoC becomes an integral part of your class design. Instead of being an "invisible helper" it becomes a first class citizen.

Instead, you should make your classes depend on your other classes:

public MyController( IQuestionBusinessLogic questionBusinessLogic )
        : base()
{   
}

and let the specific dependency resolver satisfy your dependencies. This way you free your infrastructure from the IoC dependency. Specifically, the dependency resolver is defined in the Composition Root part of your application (most probably the main project of the solution) and it is the only class that glues your classes to the specific IoC.

One of golden rules of using the IoC frameworks is "Design your classes and dependencies as if there was no IoC framework. Then, introduce one only to help you, not to make you dependant on it".



来源:https://stackoverflow.com/questions/20829070/is-it-a-preferred-approach-to-inject-iunitycontainer-itself-as-an-argument-insid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!