Just a quick question I thought I will ask to confirm I'm not introducing unnecessary trouble to my code. Is it ok to create a IDbContextFactory object directly inside LINQ, which is inside viewmodel's aggregate property like so:
public IEnumerable<ExpenseTotal> _totalsByExpenseType;
public IEnumerable<ExpenseTotal> TotalsByExpenseType
{
get
{
return (from a in _context.Expenses.Local
join b in _context.ExpenseTypes.Local
on a.ExpenseTypeID equals b.ExpenseTypeID
join c in _contextFactory.CreateDbContext().ExpenseProjections
on a.ExpenseTypeID equals c.ExpenseTypeID
where a.DateCreated >= LastSalaryDate
group a by new { a.ExpenseTypeID, b.ExpenseTypeName, c.ProjectedCost } into grp
select new ExpenseTotal
{
ExpenseTypeID = grp.Key.ExpenseTypeID,
ExpenseTypeName = grp.Key.ExpenseTypeName,
ActualCost = grp.Sum(x => x.ActualCost),
ProjectedCost = grp.Key.ProjectedCost
});
}
}
More specifically I'm asking if _contextFactory object will be disposed of properly this way? A quick search lead me to this article, which, in my understanding, suggests it's an ok approach to use?
EDIT1: The DbContextFactory is created via IServiceCollection.AddDbContextFactory<T> with ServiceLifetime.Transient option.
EDIT2: It's a WPF app with EF Core 6. The issue is (I think) that I'm using DbContextOptionsBuilder.UseLazyLoadingProxies() for my DbContext and that results in data being returned only when they are queried. So I have the main context, which is _context and then I'm calling the rest via _contextFactory when I need it using using statement, which disposes the temporary context properly.