Is it a preferred approach to inject IUnityContain

2019-07-28 19:44发布

问题:

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".