mhdrad
mhdrad

Reputation: 330

Ninject field inject not work in class with constructor

In C# MVC project, I used Ninject for IoC pattern, When I using constructor injection it works fine without any problem but when I use it as field injection, NULL reference exception occurred for _orderNotification.

public class ShopManager
{
    [Inject]
    private IOrderNotification _orderNotification;

    public ShopManager(string shopName)
    {
        //Do somethings
    }

    public int GetNotifyCount()
    {
        return _orderNotification.Count();
    }
}

Also I registered services in NinjectWebCommon,

kernel.Bind<IOrderNotification>().To<OrderNotification>();

Ninject version is 3.0

Upvotes: 1

Views: 3108

Answers (3)

Hadi Sharifi
Hadi Sharifi

Reputation: 1527

try this:

  public IOrderNotification _orderNotification;

  public IOrderNotification OrderNotification
        {
            get
            {
                return _orderNotification ??
                       (_orderNotification = DependencyResolver.Current.GetService<IOrderNotification>());
            }
            set { _orderNotification = value; }
        }

Also you can use it without constructor:

public class ShopManager
{
    [Inject]
    public IOrderNotification OrderNotification { get; set; }

    public int GetNotifyCount()
    {
        return OrderNotification.Count();
    }
}

Upvotes: 4

BatteryBackupUnit
BatteryBackupUnit

Reputation: 13233

Field injection was removed, but there is property injection which you can use instead:

public class ShopManager
{
    [Inject]
    public IOrderNotification OrderNotification { get; set; }

    public ShopManager(string shopName)
    {
        //Do somethings
    }

    public int GetNotifyCount()
    {
        return OrderNotification.Count();
    }
}

However, the recommended way to go is to use Constructor Injection. A half decent argument for property injection is when you can't control instanciation of the class or when you have inheritance where you would need to pass ctor parameters down (but remember, favor composition over inheritance!). To me your example seems simple enough to use constructor injection. Why don't you? (granted, i'm unfamiliar with asp.net mvc, so the question may seem silly).

EDIT: I verified that property injection as shown above works with ninject 3.2.2. This means i've tested it ;-) Also see https://github.com/ninject/ninject/wiki/Injection-Patterns for more info on what kinds of injection there are and when to use them.

Upvotes: 0

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

If you use Ninject 2 or higher you can't inject to field. Refer to the Things that were in Ninject 1.x that are not in Ninject 2 article for more information.

Upvotes: 3

Related Questions