在 C# MVC 项目中,我将 Ninject 用于 IoC 模式,当我使用构造函数注入(inject)时它工作正常没有任何问题但是当我将它用作字段注入(inject)时,_orderNotification 发生 NULL 引用异常。
public class ShopManager
{
[Inject]
private IOrderNotification _orderNotification;
public ShopManager(string shopName)
{
//Do somethings
}
public int GetNotifyCount()
{
return _orderNotification.Count();
}
}
我还在 NinjectWebCommon 中注册了服务,
kernel.Bind<IOrderNotification>().To<OrderNotification>();
Ninject 版本为 3.0
最佳答案
试试这个:
public IOrderNotification _orderNotification;
public IOrderNotification OrderNotification
{
get
{
return _orderNotification ??
(_orderNotification = DependencyResolver.Current.GetService<IOrderNotification>());
}
set { _orderNotification = value; }
}
你也可以在没有构造函数的情况下使用它:
public class ShopManager
{
[Inject]
public IOrderNotification OrderNotification { get; set; }
public int GetNotifyCount()
{
return OrderNotification.Count();
}
}
关于c# - Ninject 字段注入(inject)在构造函数类中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22892702/