简体   繁体   中英

How to set property or variable in constructor with Ninject (MVC3 web application)?

I have interface ITest and class Test, which implements ITest:

public Test : ITest{...}

I have such class:

public class MyClass
{
 ITest test;
 public MyClass(){...}
}

Is there any way to set new Test() example in test variable with Ninjection? I want to get rid of this code in constructor:

public MyClass()
{
 test = new Test();
}

Thanks!

I'd recommend you use constructor injection, eg:

public class MyClass {
    private readonly ITest _test;

    [Inject]
    public MyClass(ITest test) {
        _test = test;
    }
}

This provides visibility of a class dependency, ie MyClass is dependent on an instance of ITest . Ninject will automatically handle this dependency injection for you as long as you have registered an instance of ITest with the container.

Alternatively, you could use property/field injection:

public class MyClass {
    public MyClass() { }

    [Inject]
    public ITest Test { get; set; }
}

public class MyClass {
    [Inject] private ITest _test;

    public MyClass() { }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM