Reputation: 127
I'm trying to build an API using .net core, i create Entity "User", DbContext, Repository and a Controller to test if it works, but when i test it with Postman i receive always a 500 Http statu indicating an internel server error. Here is my Entity:
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[Required]
public string UserName { get; set; }
public string Email { get; set; }
[Required]
public string Password { get; set; }
public ICollection<Post> Posts { get; set; } = new List<Post>();
}
here is th DbContext:
public class NetworkDbContext : DbContext
{
public NetworkDbContext(DbContextOptions options) : base(options)
{
Database.EnsureCreated();
}
public DbSet<User> Users { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
}
here is the Repository :
public class UserRepository : IUserRepository
{
private readonly NetworkDbContext _context;
public UserRepository(NetworkDbContext context)
{
_context = context;
}
public void AddUser(User user)
{
_context.Users.Add(user);
_context.SaveChanges();
}
public IEnumerable<User> GetAllUsers()
{
return _context.Users.ToList();
}
public void RemoveUser(User user)
{
_context.Users.Remove(user);
_context.SaveChanges();
}
public void Update(User user)
{
_context.Users.Update(user);
_context.SaveChanges();
}
}
The startup.cs :
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
var connectionString = Configuration["connectionString"]; //connection string to sqlServer
services.AddDbContext<NetworkDbContext>(o => o.UseSqlServer(connectionString));
services.AddScoped<IUserRepository, UserRepository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc();
}
}
and finally here is my Controller :
[Route("api/user")]
public class UserController : Controller
{
private UserRepository _repository { get; set; }
public UserController(UserRepository repository)
{
_repository = repository;
}
[HttpPost]
public void AddUser([FromBody] User user)
{
if (user == null)
{
return BadRequest();
}
_repository.AddUser(user);
return CreatedAtRoute("GetUser", user);
}
}
In fact it indicates in the diagnostic tool an Exception : "System.InvalidOperationException", Unable to resolve service for type "SocilNetworkApi.Models.UserRepository".
Upvotes: 1
Views: 1067
Reputation: 6891
The problem is not related to EF but it's the dependency of controller
Controller is depending on UserRepository
so runtime tries to resolve that type but that's not mapped. That's why it gives you that error.
You need to make your controller dependent on IUserRepository
not on UserRepository
[Route("api/user")]
public class UserController : Controller
{
private IUserRepository _repository { get; set; }
public UserController(IUserRepository repository)
{
_repository = repository;
}
}
This should resolve your issue.
Upvotes: 1
Reputation: 1459
"SocilNetworkApi.Models.UserRepository" needs to be registered with the dependency injection container for it to be injected into the UserController constructor.
Upvotes: 0