I am trying to use dependency injection for a repository, which in Program.cs
is registered as a service. However the repository keeps getting reinstanciated each time the controller is called.
I have a feeling i need to move this to something not in the controller, and/or actually use the IServiceProvider
rarther than just declaring it. This would give it has some form of permanence, but i am not sure what/where/how to do this.
The repo is just a List<Book>
with CRUD operations and does not sit over entity framework or another data framework/database. Mostly as im just trying to learn and get an example of a repo over a list with DI in MVC. Its entirely possible that im flogging a dead horse with my approach.
I dont get any errors when navigating through my pages. When i break through the code, the operations within the repo are called fine, and do what i expect them to do. Its just when i go to my page of “view all” or “add” the repo is reset because of its reinstanciation (i presume).
Other than whats below, program.cs has not been changed.
Program.Cs
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IBookRepository, BookRepository>();
var app = builder.Build();
BookRepository.cs
public class BookRepository : IBookRepository
{
private List<Book> _books;
public BookRepository()
{
_books = new List<Book>();
}
public List<Book> GetAllBooks()
{
return _books;
}
public Book GetBookByISBN(string ISBN)
{
Book book = _books.Find(x => x.ISBN == ISBN);
return book;
}
public void CreateBook(Book book)
{
_books.Add(book);
}
public void DeleteBook(Book book)
{
_books.Remove(book);
}
}
and the LibraryController.cs constructor
public LibraryController(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException(nameof(serviceProvider));
}
_bookRepository = serviceProvider.GetService<IBookRepository>() ??
throw new ArgumentNullException(nameof(_bookRepository));
}
4