首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >什么是Ninject,你什么时候使用它?

什么是Ninject,你什么时候使用它?
EN

Stack Overflow用户
提问于 2013-06-29 07:49:17
回答 1查看 47.1K关注 0票数 59

我一直在帮助几个朋友做一个项目,有一个类使用了Ninject。我是C#的新手,我不知道这个类在做什么,这就是为什么我需要理解C#的原因。有没有人能解释一下Ninject是什么,什么时候使用它(如果可能的话,举例说明)?或者,如果你能指出一些链接,那也是很棒的。

我尝试了这个问题:Ninject tutorials/documentations?,但它对像我这样的初学者没有真正的帮助。

EN

回答 1

Stack Overflow用户

发布于 2021-01-15 17:02:14

您必须首先了解依赖注入(DI)。请注意,

代码语言:javascript
复制
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 */

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17375234

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档