7

我通过从 web.config 派生NinjectHttpApplicationNinjectHttpModule在我的 web.config 中使用我的 Global 成功地在我的 Web 应用程序中使用了 Ninject

我现在想做的是在我的一个类库中使用 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是空的,所以我显然做错了。

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

public Class1([Inject] ICustomerRepository repository)

我将如何实例化Class1

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

4

1 回答 1

3

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

Ninject - 如何以及何时注入

于 2009-09-25T12:27:04.233 回答