1、在namespace ClassLibrary下定义接口及实现的类:
public interface IClass {
void Hello();
}
public class Class1 : IClass
{
public void Hello()
{
HttpContext.Current.Response.Write("Class1::Hello");
}
}
public class Class2 : IClass
{
public void Hello()
{
HttpContext.Current.Response.Write("Class2::Hello");
}
}
2、定义Module:
public class Module1 : NinjectModule
{
public override void Load()
{
//throw new NotImplementedException();
//Bind<IClass>().To<Class1>();
Type type = Type.GetType("ClassLibrary.Class1");
Bind<IClass>().To(type);
}
}
public class Module2 : NinjectModule
{
public override void Load()
{
Bind<IClass>().To<Class2>();
}
}
Module2采用了硬编码,只能调用Class2的实现方法,而Module1则通过类型参数值“ClassLibrary.Class1”解析为Class1的实现方法,这样做比较灵活,在实际应用中我们可以从配置文件里读取,以确定实现方法
3、定义Client
public class Client
{
private readonly IClass inst;
[Inject]
public Client(IClass cls)
{
if (cls == null)
throw new ArgumentNullException("cls");
this.inst = cls;
}
[Inject]
public IClass Cls
{
get;
set;
}
public void SayHello()
{
this.inst.Hello();
}
}
4、在页面里调用:
以下代码可以放在页面的Page_Load方法里
using (IKernel kernel = new StandardKernel(new Module1()))
{
Client client = kernel.Get<Client>();
client.SayHello();
}
using (IKernel kernel = new StandardKernel(new Module2())) {
Client client = kernel.Get<Client>();
client.SayHello();
client.Cls = kernel.Get<IClass>();
client.Cls.Hello();
}
using (IKernel kernel = new StandardKernel(new Module1()))
{
IClass cls = kernel.Get<IClass>();
cls.Hello();
}