【发布时间】:2016-07-07 06:27:47
【问题描述】:
我正在开发一个 Asp.Net Mvc 项目。在我的项目中,我所有的控制器都继承自 BaseController。我在 BaseCotroller 中做最常见的事情。我正在使用 Ninject 进行依赖注入。但是我在向 BaseController 注入依赖时遇到了问题。
这是我的基础控制器
public class BaseController : Controller
{
protected ICurrencyRepo currencyRepo;
public Currency Currency { get; set; }
public BaseController()
{
this.currencyRepo = new CurrencyRepo();
}
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
Currency cur = null;
base.Initialize(requestContext);
Url = new UrlHelperAdaptor(base.Url);
string currencyIdString = HttpContext.Application["currency"].ToString();
if(string.IsNullOrEmpty(currencyIdString))
{
cur = currencyRepo.Currencies.FirstOrDefault(x => x.Default);
}
else
{
int id = Convert.ToInt32(currencyIdString);
cur = currencyRepo.Currencies.FirstOrDefault(x => x.Id == id);
}
if (cur == null)
{
cur = currencyRepo.Currencies.FirstOrDefault();
}
if(cur!=null)
{
AppConfig.CurrentCurrencyUnit = cur.Unit;
AppConfig.CurrentCurrencyMmUnit = cur.MmUnit;
}
Currency = cur;
}
}
如您所见,我必须在不使用 Ninject 的情况下在构造函数中启动 CurrencyRepo 的实例。
我想要的构造函数是这样的
public BaseController(ICurrencyRepo repoParam)
{
this.currencyRepo = repoParam;
}
但是如果我这样做并运行我的项目,它会给我如下错误。
那么如何在 BaseController 中使用 ninject 注入依赖项?
【问题讨论】:
标签: asp.net-mvc dependency-injection ninject ninject.web.mvc