我一直在帮助几个朋友做一个项目,有一个类使用了Ninject。我是C#的新手,我不知道这个类在做什么,这就是为什么我需要理解C#的原因。有没有人能解释一下Ninject是什么,什么时候使用它(如果可能的话,举例说明)?或者,如果你能指出一些链接,那也是很棒的。
我尝试了这个问题:Ninject tutorials/documentations?,但它对像我这样的初学者没有真正的帮助。
发布于 2021-01-15 17:02:14
您必须首先了解依赖注入(DI)。请注意,
public interface IService
{
void Serve();
}
public class Service1 : IService
{
public void Serve() {
Console.WriteLine("Service1 Called");
}
}
public class Service2 : IService
{
public void Serve() {
Console.WriteLine("Service2 Called");
}
}
public class Service3 : IService
{
public void Serve() {
Console.WriteLine("Service3 Called");
}
}
public class Client
{
private IService service;
public Client(IService _service) //Constructor injection
{
service = _service;
}
public void ServeMethod() {
service.Serve(); //Notice here, this Serve() method has no idea what to do.
} // runtime will assign the object, that is Ninject
}
class Program
{
static void Main(string[] args)
{
IService s1 = new Service1(); //N.B. Ninject assigns object with interface
Client c1 = new Client(s1);
c1.ServeMethod();
IService s2 = new Service2(); //N.B. Ninject assigns object with interface
c1 = new Client(s2);
c1.ServeMethod();
IService s3 = new Service3(); //N.B. Ninject assigns object with interface
c1 = new Client(s3);
c1.ServeMethod();
Console.ReadKey();
}
}
// Ninject creates object in runtime for interface in runtime in ASP.NET MVC project.
/*输出:
Service1已调用
Service2已调用
调用的Service3 */
https://stackoverflow.com/questions/17375234
复制相似问题