Ninject可以帮助我们解耦,提高类的内聚度,它的使用非常简单,看下面代码:
首先下载Ninject.dll这个动态链接库文件,可以到DLL大全里下载
public interface ISay
{
void Write(string message);
}
public class ChinaSay : ISay
{
public void Write(string message)
{
Console.WriteLine(String.Format("早上,中国人说:{0}", message));
}
}
public class USASay : ISay
{
public void Write(string message)
{
Console.WriteLine(String.Format("早上,美国人说:{0}", message));
}
}
internal class MyModule : Ninject.Modules.NinjectModule
{
public override void Load()
{
Bind<ISay>().To<USASay>();
}
}
调用也十分方便 :
IKernel kernel = new StandardKernel(new MyModule());
ISay logger = kernel.Get<ISay>();
logger.Write("早上好");
当然如果不使用Ninject也可以通过其它方法实现依赖注入,比如构架函数,看代码:
/// <summary>
/// 构架函数的依赖注入
/// </summary>
internal class Factory : ISay
{
ISay _isay;
public Factory(ISay isay)
{
this._isay = isay;
}
#region ISay 成员
public void Write(string message)
{
this._isay.Write(message);
}
#endregion
}