Incorrect error message when using constructor params?

Oct 30, 2010 at 6:34 AM

I think I've spotted a dodgy error message when you're specifying constructor parameters in configuration.  I've repro'd it in a separate project which I can post if it helps.

I came across it whilst playing with named registrations (which I'd not used up to this point).  The situation is that you're resolving something like this:

public Widget(IFlange flange, ISprocket sprocket)

(this is the only defined .ctor) and the registrations for the dependencies are, say:

  <register type="IFlange" mapTo="Flange" name="superFlange"/>
  <register type="ISprocket" mapTo="Sprocket" />

If you they register the IWidget as:

      <register type="IWidget" mapTo="Widget">
        <constructor>
          <param name="flange" type="IFlange" dependencyName="superFlange" />
        </constructor>
      </register>

You get as InvalidOperationException: "Configuration is incorrect, the type DependencyInjection1.Widget does not have a constructor that takes parameters named flange."  But as you can see, this is not true.  It does.  It's just that another parameter is required.  If it said "[...] does not have a constructor that only takes parameters named flange." it would not only be true but it would imply that I should be specifying more parameters in my config.

My early experience of Unity was that if something wasn't specified, it took the obvious route.  If I have a Widget class in my project and it's not been registered but I ask Unity to get me an instance it, it does.  Since I'd already told Unity how to resolve ISprockets, I didn't expect to have to do it again.  I'm sure it's in the documentation but as Cwalina/Abrams [1] said "many developers expect to learn the basics of new frameworks very quickly.  They want to do it by experimenting with parts of the framework..."

Anyway, I didn't raise it in the Issue Tracker as there's always the possibility that it should've worked and I did something wrong.  Again.

 

[1] Framework Design Guidelines, 2009, Microsoft Corporation (Section 2.2.2 - can't give page reference, read it on Kindle)

 

 

Oct 30, 2010 at 8:13 PM

Well, we could make the error message more explicit. But your comments about inconsistency aren't really true. Unity doesn't guess. It uses some very simple strategies:

If you configure a constructor, it looks for exactly and only what you told it. If it doesn't match, you get an error.

If you don't configure a constructor, it picks the one with the most parameters. If there are multiple possible ones, you get an error.

The problem with the behavior that you're proposing is, what if there are multiple constructors taking a parameter named "flange"? What algorithm should we pick to choose? Also consider the performance implications here, since reflecting over things takes time.

I agree we could improve the error message here, but I disagree that it's being inconsistent.