Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Two things I don't like:</p> <ol> <li>Creating a kernel inside the <code>AddForm</code> method. This should never happen, as it inverts the IoC pattern -- instead, the class that <code>AddForm</code> belongs to should request any dependencies it needs.</li> <li>The use of magic strings. It doesn't seem right to require the consumers of <code>AddForm()</code> to send a string naming the strategy.</li> </ol> <p>I'm not quite sure how to resolve this; one thing that comes to mind is to add a <code>Func&lt;string, IPFormDataStrategy&gt;</code> dependency to the class that owns <code>AddForm</code> (call it class X). I'm imagining something like this:</p> <pre><code>namespace Web.Services { public class X { private readonly Func&lt;string, IPFormDataStrategy&gt; _strategyResolver; public X(Func&lt;string, IPFormDataStrategy&gt; strategyResolver) { _strategyResolver = strategyResolver; } public bool AddForm(XmlDocument form, string formName) { return _strategyResolver(formName).DoWork(form); } } } </code></pre> <p>Then you can use <code>ToMethod</code> to bind <code>Func&lt;string, IPFormDataStrategy&gt;</code>:</p> <pre><code>public class FormsModule : NinjectModule { public override void Load() { Bind&lt;FormAStrategy&gt;().ToSelf(); Bind&lt;FormBStrategy&gt;().ToSelf(); Bind&lt;Func&lt;string, IPFormDataStrategy&gt;&gt;().ToMethod(context =&gt; new Func&lt;string, IPFormDataStrategy&gt;(formName =&gt; { switch (formName) { case "FormA": return context.Kernel.Get&lt;FormAStrategy&gt;(); // Note, could also simply "return new FormAStrategy()" here. case "FormB": return context.Kernel.Get&lt;FormBStrategy&gt;(); default: throw new InvalidOperationException(formName + " is unrecognized"); } }) ); } } </code></pre> <p>You may find this needlessly complex, and maybe it is ... I like it because it makes class X's dependency explicit (that is, get a strategy given a form name), rather than giving it access to the entire kernel. This approach also consolidates the logic for getting a strategy into a single switch statement. It still relies on the magic strings, but I'm not sure how to get around that, without knowing more context ...</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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