I am a newbie struggling with IoC and DI. I would like to dynamically allow connection and factory connection using autofac (or any other suitable .NET IoC tool).
The script can change the connection implementation to another with a lot of tracing options, etc.
When I apply DI and IoC to the code below, I get namedParameter clutter in constructors, etc. The factory connection returns a new connection with a unique port (silly example, just to show that I need to save some kind of state in the factory)
I suppose I could use property injection for the IP range and port, but in this case I am not guaranteed that the connections will have an IP or port, which is the constructor point. Also, named parameters make me depend on argument names.
IoC ideas, templates, pointers are greatly appreciated!
Update:
More specifically: how can I change the connection class for injections? Should I go with an injection of property? Or any tricks I could do could get a safer solution with constructor arguments?
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 {
Now use:
//Register builder.RegisterType<Connection>().As<IConnection>(); builder.RegisterType<ConnectionFactory>().As<IConnectionFactory>().SingleInstance(); ... var connection = container.Resolve<IConnectionFactory>( new NamedParameter("ip", "127.0.0.1"), new NamedParameter("fromPort", 80).CreateConnection());
Larsbj
source share