dependency-injection - 类库中带有 Ninject 的 DI

标签 dependency-injection ninject

这个问题在这里已经有了答案:





Ninject - how and when to inject

(2 个回答)


8年前关闭。




通过从 NinjectHttpApplication 派生我的 Global,我在我的 Web 应用程序中成功使用了 Ninject并使用 NinjectHttpModule在我的 web.config

我现在想做的是在我的一个类库中使用 DI,但我不知道该怎么做。我有以下虚拟类:

/// <summary>
/// Testing Ninject DI in a class library
/// </summary>
public class Class1
{
    [Inject]
    ICustomerRepository CustomerRepository { get; set; }

    public string SomeText { get; set; }

    public Class1(string text)
    {
        MyConfig config = new MyConfig();
        config.Configure();

        SomeText = text;
    }

    public Customer GetCustomer()
    {
        var customer = CustomerRepository.GetCustomer();
        return customer;
    }
}

public class MyConfig
{
    public IKernel Configure()
    {
        IKernel kernel = new StandardKernel(new NinjectRepositoryModule());
        return kernel;
    }
}

当我实例化 Class1并调用GetCustomer() , CustomerRepository是空的,所以我显然做错了什么。

另外,如果我使用构造函数注入(inject)并让我的构造函数像

public Class1([Inject] ICustomerRepository repository)

我将如何实例化 Class1 ?

Ninject 很新,所以这一切都非常容易。

最佳答案

看起来我已经知道该怎么做 - 哎呀 :)

Ninject - how and when to inject

关于dependency-injection - 类库中带有 Ninject 的 DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1476826/

相关文章:

architecture - 最具争议的帖子,IoC,Ninject,只是让东西工作

c# - 使用 Ninject 启动 MVP WinForms 应用程序

asp.net-mvc - Ninject、MVC 和 session 范围 : Reasonable Practice?

java - 为每个租户自定义 Spring @Scope

c# - 具体 .Net 类的依赖注入(inject)

c# - 批量注册开放通用实现

rest - Web Api 2 + OWIN 3 + NInject.Web.WebApi.OwinHost,仅在启动时出错

c# - 使用 Ninject 初始化具有初始值的字段

javascript - 如何在 AngularJS 上放置服务?

scala - Scala 中基于角色的编程框架/面向复合的编程框架