Note that there are some explanatory texts on larger screens.

plurals
  1. POShould I use a nested class or an IoC container?
    text
    copied!<p>I have two classes, Server and Client. Server needs to instantiate Client in multiple threads and Client has a virtual member that needs to provide a custom implementation. My question is. Should the Client class be a nested class of the Server class or should I use an Interface and Dependency Injection to get the custom implementation into the Server class. Now the Client class also has many private methods that provide some standard logic that shouldn't be changed.</p> <pre><code>public class Server { public void DoWork() { for (var i = 0;i &lt; 10; i++) { Client client = new Client(); client.Process(i); } } } public class Client { private void doSomething() { ... } // Needs to be overridden and provide custom logic public virtual string Process(int i) { return i.ToString(); } } </code></pre> <p>Working example:</p> <pre><code>public interface IClient { string Process(string message); } public abstract class Client : IClient { public virtual string Process(string message) { return message; } } public class CustomClient : Client { public CustomClient() { } public override string Process(string message) { return string.Format("Custom Client:{0}", message); } } public class Server { private Func&lt;IClient&gt; createClient; public Server() { } public Server(Func&lt;IClient&gt; client) { createClient = client; } public void DoWork() { for (var i = 0; i &lt; 10; i++) { IClient = client = createClient(); client.Process(string.Format("Client #{0}", i)); } } } </code></pre> <p>Test Program...you would step through to see it hit the CustomClient</p> <pre><code>class Program { static void Main(string[] args) { Func&lt;CustomClient&gt; factory = () =&gt; new CustomClient(); var server = new Server(factory); server.DoWork(); } } </code></pre>
 

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