I'm trying to setup dependency injection in my Xamarin Forms application. I have got constructor injection all working with Simple Injector. However, when I start to use Entity Framework I am struggling with the following issue.
I register my AppDbContext (inherits from DbContext) with the following lines:
_container.Register<AppDbContext>(() => {
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>().UseSqlServer(connectionString).Options);
});
This throws the error below:
-[Disposable Transient Component] AppDbContext is registered as transient, but implements IDisposable...
So I then change the lines above to:
_container.Register<AppDbContext>(() => {
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>().UseSqlServer(connectionString).Options);
}, Lifestyle.Scoped);
And also set the defaultscopedlifestyle to the below:
_container.Options.DefaultScopedLifestyle = new ThreadScopedLifestyle();
This throws the below error:
AppDbContext is registered using the 'Thread Scoped' lifestyle, but the instance is requested outside the context of an active (Thread Scoped) scope.
Finally I change the defaultscopedlifestyle to the only other option I can find:
_container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
But then I receive this error below:
AppDbContext is registered using the 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope. Please see https://simpleinjector.org/scoped for more information about how apply lifestyles and manage scopes.
All I need to do is to register the AppDbContext so that it can be used with entity framework. I use the following line in my MVC project which shares the same shared class library:
services.AddDbContext<AppDbContext>
So I need to be able to do the above line with simple injector.
Hope this is enough information, if you need to know anything else feel free to ask.
Update 5th Feb
One of my repositories:
public class HolidayBookingRepository : IHolidayBookingRepository
{
private readonly AppDbContext context;
public HolidayBookingRepository(AppDbContext context)
{
this.context = context;
}
public async Task<HolidayBooking> GetById(int Id)
{
return await context.HolidayBooking.AsNoTracking().Where(h =>h.HolidayBookingId == Id).FirstOrDefaultAsync<HolidayBooking>();
}
}
My ViewModel:
IHolidayBookingRepository _holidayRepo;
public HomePageViewModel(IHolidayBookingRepository holidayRepo)
{
_holidayRepo = holidayRepo;
}
public override async void OnAppearingAsync()
{
try
{
base.OnAppearingAsync();
HolidayBooking booking = await _holidayRepo.GetById(42);
Console.WriteLine(booking.Comment);
}
catch(Exception ex)
{
}
}