Hello
Stuff, i learned recently
For example, there is peace of code:
public partial class MainWindow : Window
{
ISubject _subject;
public MainWindow()
{
_subject = new WeatherData();
}
.... other code....
}
What is a problem with this code?
a couple of.
1. MainWindow should to know about ISubject realization. So, it violate OCP. Class MainWindow do some job and it also instantiate _subject by concrete realization.
2. If i will want other _subject realization, i will open MainWindow and do changes. It is violates OCP.
3. It is not using Ninject dependency injector ;-)
So, how we fix it?
1. In Visual studio package manager console type :
PM> install-package Ninject
2. Create class, which bind interface and realization by using Ninject:
public class SubjectModule : NinjectModule
{
public override void Load()
{
Bind<ISubject>().To<WeatherData>();
}
}
what is mean, is realization of ISubject is WeatherData
3. Lets create some factory, which use SubjectModule :
public class SubjectFactory
{
public static ISubject Create()
{
IKernel krnl = new StandardKernel(new SubjectModule());
return krnl.Get<ISubject>();
}
}
4. lets do refactoring to MainWindow :
public partial class MainWindow : Window
{
ISubject _subject;
public MainWindow()
{
_subject = SubjectFactory.Create();
}
.... other code....
}
that all!
Now we can change Binding and get other realization inside of MainWindow without change its code! And, from now, MainWindow should not know anything about _subject concrete realization
Enjoy
P.S. thanks to Vova about make me to learn it
x
No comments:
Post a Comment