Unity Framework IoC with default constructor

前端 未结 2 1182
误落风尘
误落风尘 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<UserService>(new InjectionConstructor());  
    

    Using XML config:

    <container>
      <register type="UserService">
        <constructor />
      </register>
    </container>
    
    0 讨论(0)
  • 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<IUserService, UserService>()
            .RegisterType<IFacebookService, FacebookService>();
    }
    

    IUserRepository is not registered. Add a line like

    .RegisterType<IUserRepository, UserRepository>()
    
    0 讨论(0)
提交回复
热议问题