Reputation: 21097
Tried to clarify my problem
I have a ASP.NET 5 Web Api application. I'm trying to create a controller class that makes use of a custom base controller. As soon as I add a constructor to the base controller then MVC can no longer find the Get()
end point defined in the Generic
class.
This works:
When I navigate to /api/person
then the Get()
end point is triggered defined in the Generic
class
Generic:
public class Generic
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
PersonController
[Route("api/[controller]")]
public class PersonController : Generic
{
}
This doesn't work
When I navigate to /api/person
then the Get()
end point is not triggered. The only thing that is added is a constructor in both the Generic
class and the PersonController
class.
public class Generic
{
protected DbContext Context { get; set; }
public Generic(DbContext context)
{
Context = context;
}
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
PersonController
[Route("api/[controller]")]
public class PersonController : Generic
{
public PersonController(DbContext context) : base(context) { }
}
Is this a bug or am I doing something wrong?
Upvotes: 1
Views: 3270
Reputation: 218952
Your problem has nothing to do with inheriting from another base class. I think the problem is, a proper implementation of your DbContext
is not being injected to the constructor. Since asp.net 5 is so modular/dependency injectable, you need to explicitly configure it.
In the ConfigureServices
method in your Startup.cs class, register your DbContext
service so MVC will use that and inject that to your class controller when needed.
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddDbContext<DbContext>();
services.AddMvc();
}
Upvotes: 2