I use EfFeatureDal class as a database connection class and i use constructor for this connection. But when i need to call this class from FeatureList i cant add these connection constructor’s parameters thats why i need base constructor on EfFeatureDal but i cant add it?
public class FeatureList:ViewComponent
{
FeatureManager featureManager = new FeatureManager(new EfFeatureDal());
public IViewComponentResult Invoke()
{
return View();
}
}
public class EfFeatureDal : GenericRepository<Feature>, IFeatureDal
{
public EfFeatureDal(Context1 _db) : base(_db)
{
}
public EfFeatureDal() { }
}
I got this error on base constructor:
Error CS7036 There is no argument given that corresponds to the
required parameter ‘_db’ of
‘GenericRepository.GenericRepository(Context1)’
public class FeatureList:ViewComponent
{
FeatureManager featureManager = new FeatureManager(new EfFeatureDal());
public IViewComponentResult Invoke()
{
return View();
}
}
I got this error when i delete base constructor on new FeatureManager(new EfFeatureDal()):
Error CS7036 There is no argument given that corresponds to the
required parameter ‘_db’ of ‘EfFeatureDal.EfFeatureDal(Context1)’
2
Answers
The mistake that you made is you are trying to instantiate EfFeatureDal manually and you got stuck in the trap, actually you need to know about DI(Dependency Injection) Concept and use a IoC container to instantiate and inject EfFeatureDal object in your derived objects.
you can see a sample here
Well, It would be perfect it if you would have been shared FeatureManager details. However, If your EfFeatureDal class has implicitly defined a constructor within it as following:
As it has constructor dependency, you must have to pass the constructor if you would like to create its instance somewhere. But this is not the common practice we do everyday.
What you can do is, if you need to access EfFeatureDal methods or anything you have defined there, you can call it in derived class by injecting its interface within derived class constructor. Have a look in following example:
Output:
Alternatively:
If you have defined FeatureManager as following:
In that scenario, if you would like to call EfFeatureDal in your FeatureList derived class you have to pass DbContext as its constructor parameter. You can do that in following manner:
Note: We are passing _context to EfFeatureDal because it has constructor dependency that is
public EfFeatureDal(ApplicationDbContext context) : base(context) { }
. Thus, Always keep in mind base-class constructor should be called when creating instances of the derived class. I would recommend you to check our official document for more details.