Note that there are some explanatory texts on larger screens.

plurals
  1. POIoC, factories and constructor arguments
    text
    copied!<p>I'm a beginner struggling with IoC and DI. I'd like to be able to resolve the connection and connection factory dynamically using autofac (or any other suitable .NET IoC tool). </p> <p>A scenario could be changing the connection implementation to another one with more facilities for tracing etc.</p> <p>When I apply DI and IoC to the code below, I get a mess of namedParameter in constructors etc. The connection factory returns a new connection with a unique port (silly example, just to show I need to keep some sort of state in the factory)</p> <p>I figure I could use property injection for the IP and port range, but that way, I wouldn't be guaranteed that the connections would have an IP or port, which is the point of a constructor. Also, the named parameters make me dependent on the names of the arguments as well.</p> <p>Ideas, patterns, IoC pointers are much appreciated! </p> <p><strong>Update:</strong></p> <p>More specific: How could I change the connection class to be injectable? Should I go with property injection? Or any tricks I could do get a more type-safe resolving with constructor arguments?</p> <pre><code>public interface IConnection { void Open(); void Close(); string Execute(string command); } public interface IConnectionFactory { IConnection CreateConnection(); } public class Connection : IConnection { ... public Connection(String ip, int port) { _ip = ip; _port = port; } public string Execute() {} public void Open() {} public void Close() {} } public class ConnectionFactory : IConnectionFactory { //How would I resolve this? public ConnectionFactory(string ip, int fromPort) { ... } public IConnection CreateConnection() { //How would I resolve this? return new Connection(ip, fromPort++); } } </code></pre> <p>Now, the usage:</p> <pre><code>//Register builder.RegisterType&lt;Connection&gt;().As&lt;IConnection&gt;(); builder.RegisterType&lt;ConnectionFactory&gt;().As&lt;IConnectionFactory&gt;().SingleInstance(); ... var connection = container.Resolve&lt;IConnectionFactory&gt;( new NamedParameter("ip", "127.0.0.1"), new NamedParameter("fromPort", 80).CreateConnection()); </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