【问题标题】:DI with Ninject in a Class Library [duplicate]类库中带有 Ninject 的 DI [重复]
【发布时间】:2009-09-25 11:39:22
【问题描述】:

通过从NinjectHttpApplication 派生我的全局并在我的web.config 中使用NinjectHttpModule,我成功地在我的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 来说还很陌生,所以这一切都非常简单。

【问题讨论】:

    标签: dependency-injection ninject


    【解决方案1】:

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

    Ninject - how and when to inject

    【讨论】:

    • 这很有趣
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多