Unity Framework IoC with default constructor

前端 未结 2 1201
误落风尘
误落风尘 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:36

    I can't speak to Unity specifically, but IoC containers will generally try to use the most specific constructor they can find because it's a constructor.

    If there's a constructor that takes two dependencies for injection, then presumably they are required for using the object; the default constructor will have to do something to fulfill them if the container calls it. The container's job is to fulfill dependencies, so why would it leave it up to the class to do that if it were not instructed to leave it up to the class?

    To your specific question, according to your code:

    private static void RegisterContainer(IUnityContainer container)
    {            
        container
            .RegisterType()
            .RegisterType();
    }
    

    IUserRepository is not registered. Add a line like

    .RegisterType()
    

提交回复
热议问题