The adventure of writing meaningful code.
Inversion of Control
StructureMap Multiple Parameters
Jul 3rd
One of the common questions about IOC is how to pass parameters. This question is specially common with StructureMap since a lot of the old methods have been deprecated.
Here is a quick Example:
public class DataSource : IDataSource
{
public DataSource(string URL, string account, string password)
{
//your code here
}
}
ObjectFactory.Initialize(x =>
{
x.For<IDataSource>().Use<DataSource>()
.Ctor<string>("URL").Is(URL)
.Ctor<string>("account").Is(account)
.Ctor<string>("password").Is(password)
;
}
and you can call it like this:
private IDataSource ds = ObjectFactory.GetInstance<IDataSource>();
There is a huge amount of benefits as I mentioned in my previous post, including saving a lot of typing since all parameters are preconfigured.
Unitiy IOC
Feb 11th
Basically, with Unity, I ended up writing something like this (simplified version) :
IUnityContainer container = new UnityContainer(); container.RegisterType<IRiskRepository, RiskRepository>(); string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; container.Configure<InjectedMembers>().ConfigureInjectionFor<RiskRepository>(new InjectionConstructor(conn)); UnityControllerFactory factory = new UnityControllerFactory(container); ControllerBuilder.Current.SetControllerFactory(factory);
Unity turned out to work very well. I was able to save a lot of lines of code and it is greatly improving the testability of the dynamic modules I am using on the mock project architecture. Also, it was easy to set up. Its a good alternative to the other more popular IOC.
Inversion of Control
Feb 4th
If you are building an application that has a lot of modules and those modules can be plugged in dynamically then you will probably want to use inversion of control (IoC).
What can inversion of control do for you?
- help you deal with the configuration of all the modules
- a one “single point change” so you wont have to hunt down every other place where things could go wrong
- help with transparency as you just have to use a module and not worry how it is implemented
- provide a nice way to have strong contracts (due to interfaces)
- finally, the application can change it’s own behavior when it believes it is necessary at runtime
If you want to learn more I would recommend reading the the famous article written by Martin Fowler.