Here you will find 2 samples that I wrote to help me materializing the "magic" of Ninject and more generally of DI.
using System;
using Ninject;
using Ninject.Modules;
namespace simplInject {
class Program {
static void Main (string[] args) {
IKernel ik = new StandardKernel(new imod());
//constructor with 2 interfaces.
I3 c = ik.Get<I3>(); // will "magically" instanciate C1 and C2 instances from the binding
Console.WriteLine("{0} with {1} C1 instance", c.concat, C1.cpt);
//constructor with 1 interface and 1 parameter.
I4 c4 = ik.Get<I4>(); // // will "magically" instanciate another C1 instance from the binding
Console.WriteLine("{0} with {1} C1 instance", c4.concat, C1.cpt);
}
}
class imod : NinjectModule {
public override void Load () {
//Here the WithconstructorArgument is to trace the binding in the main method.
Bind<I1>().To<C1>().WithConstructorArgument("s", "string I");
Bind<I2>().To<C2>().WithConstructorArgument("s", "string II");
Bind<I3>().To<C3>();
Bind<I4>().To<C4>().WithConstructorArgument("s", "string III");
}
}
public interface I1 {
string s1 { get; set; }
}
public interface I2 {
string s2 { get; set; }
}
public interface I3 {
string concat { get; }
}
public interface I4 {
string concat { get; }
}
public class C1 : I1 {
public static int cpt = 0;
private int _id;
string _s;
public C1 (string s) {
_id = C1.cpt++;
_s = s;
}
public int Id { get { return _id; } }
public string s1 {
get { return this._s; }
set { this._s = value; }
}
}
public class C2 : I2 {
string _s;
public C2 (string s) {
this._s = s;
}
public string s2 {
get { return this._s; }
set { this._s = value; }
}
}
public class C3 : I3 {
I1 _c1; I2 _c2;
public C3(I1 c1, I2 c2) {
_c1 = c1; _c2 = c2;
}
public string concat {
get { return _c1.s1 + " " + _c2.s2; }
}
}
public class C4 : I4 {
I1 _c1; string _s;
public C4 (string s, I1 c1) {
_c1 = c1;
_s = s;
}
public string concat {
get { return _s + " " + _c1.s1; }
}
}
}
Aucun commentaire:
Enregistrer un commentaire