Reputation: 14831
I am developing an Asp.Net Mvc project. In my project, all my controllers inherit from a BaseController. I do most common stuffs in BaseCotroller. I am using Ninject for dependency injection. But I am having a problem with injecting dependency to BaseController.
This is my 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;
}
}
As you can see, I have to initiate the instance of CurrencyRepo in the constructor without using Ninject.
What I want constructor is to be like this
public BaseController(ICurrencyRepo repoParam)
{
this.currencyRepo = repoParam;
}
But if I do that way and run my project, it gives me error as follow.
So how can I inject dependency using ninject in BaseController?
Upvotes: 1
Views: 580
Reputation: 200
Why you do your Dependency Injection In your BaseController Constructor. The proper way is to do it in the Constructor of the Controller where you want to use it.
Delete this from BaseController
public BaseController()
{
this.currencyRepo = new CurrencyRepo();
}
change this protected ICurrencyRepo currencyRepo;
to this protected ICurrencyRepo CurrencyRepo;
And add at a Controller who inherits from the BaseController this:
public WishListController(ICurrencyRepo currencyRepo)
{
CurrencyRepo = currencyRepo;
}
Upvotes: 0
Reputation: 49133
You have to change your derived types (WishListController
, CartController
etc...) constructor to pass the required parameter (ICurrencyRepo
) to the base controller constructor.
Something like:
public class WishListController : BaseController
{
public WishListController(ICurrencyRepo currencyRepo) : base(currencyRepo)
{
}
}
See MSDN
Upvotes: 2