Unity Framework IoC with default constructor

前端 未结 2 1203
误落风尘
误落风尘 2021-01-12 00:54

I\'m trying to inject a dependency to my MVC controllers like this

private static void RegisterContainer(IUnityContainer container)
{            
    contain         


        
2条回答
  •  误落风尘
    2021-01-12 01:31

    The Unity default convention (which is pretty clearly spelled out in the documentation) is to choose the constructor with the most parameters. You can't just make a blanket statement that "it's not true that IoC will find the most specific constructor , if you don't specify the constructor parameters while registering a type , it will automatically call default constructor." Each container implementation can and does have different defaults.

    In Unity's case, like I said, it will choose the constructor with the most parameters. If there are two that have the most parameters, then it'll be ambiguous and throw. If you want something different, you must configure the container to do that.

    Your choices are:

    Put the [InjectionConstructor] attribute on the constructor you want called (not recommended, but quick and easy).

    Using the API:

    container.RegisterType(new InjectionConstructor());  
    

    Using XML config:

    
      
        
      
    
    

提交回复
热议问题