Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is nothing magical going on. You are specifying concrete types, so naturally they are resolvable, because if we have the <code>Type</code> object, we can call a constructor on it.</p> <pre><code>class Fred { }; Fred f1 = new Fred(); Type t = typeof(Fred); Fred f2 = (Fred)t.GetConstructor(Type.EmptyTypes).Invoke(null); </code></pre> <p>The last line above is effectively what happens, the type t having been found by using <code>typeof</code> on the type parameter you give to <code>Resolve</code>.</p> <p>If the type cannot be constructed by new (because it's in some unknown separate codebase) then you wouldn't be able to give it as a type parameter to <code>Resolve</code>.</p> <p>In the second case, it is constructor injection, but it's still a known concrete constructable type. Via reflection, the Unity framework can get an array of all the Types of the parameters to the constructor. The type <code>TestWhatever</code> is constructable, so there is no ambiguity or difficulty over what to construct.</p> <p>As to your concern about separate modules (assemblies), if you move <code>TestWhatever</code> to another assembly, that will not change the lines of code you've written; it will just mean that you have to add a reference to the other assembly to get this one to build. And then <code>TestWhatever</code> is still an unambiguously refeferenced constructable type, so it can be constructed by Unity.</p> <p>In other words, if you can refer to the type in code, you can get a <code>Type</code> object, and so at runtime it will be directly constructable.</p> <p><strong>Response to comment:</strong></p> <p>If you delete the class <code>TestWhatever</code>, you will get a compile-time error, because you refer to that type in your code. So it won't be possible to get a runtime by doing that.</p> <p>The decoupling is still in effect in this arrangement, because you could register a specific instance of <code>TestWhatever</code>, so every call to <code>Resolve&lt;TestWhatever&gt;()</code> will get the same instance, rather than constructing a new one.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload