I have an application with two DbContexts - ApplicationDbContext (from IdentityDbContext) and my own IMSDbContext (from a db-first scaffolding).
I am trying to inject a Repository (based on my own dbContext) into ApplicationUser without success:
startup.cs:
services.AddDbContext<IMSDBContext>(options => options.UseSqlServer(IMSConnString));
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(IdentityConnString));
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
Repository:
public interface IGenericRepository<T> where T: class
{
Task<IList<T>> GetAll(
Expression<Func<T, bool>> expression = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
List<string> includes = null);
Task<T> Get(Expression<Func<T, bool>> expression,List<string> includes=null);
Task Insert(T entity); etc...
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private readonly IMSDBContext _context;
private readonly DbSet<T> _db;
public GenericRepository(IMSDBContext context)
{
_context = context;
_db = _context.Set<T>();
}
public async Task<IList<T>> GetAll(Expression<Func<T, bool>> expression = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, List<string> includes = null)
{
IQueryable<T> query = _db;
if (expression != null)
{
query = query.Where(expression);
}
if (includes != null)
{
foreach (var includeProperty in includes)
{
query.Include(includeProperty);
}
}
if (orderBy != null)
{
query=orderBy(query);
}
return await query.AsNoTracking().ToListAsync();
} etc..
ApplicationUser.cs
public class ApplicationUser : IdentityUser
{
private IGenericRepository<Departments> _genericRepositoryDepts;
public ApplicationUser(IGenericRepository<Departments> genericRepositoryDepts)
{
_genericRepositoryDepts = genericRepositoryDepts;
}
public Int16 Employee_id { get; set; }
public List<int> DepartmentsManaged()
{
var c = _genericRepositoryDepts.GetAll(x=>x.Manager==this.Employee_id).Result.Select(x => x.id);
return c.ToList();
}
Running the code generates an exception in UserManager:
System.InvalidOperationException: 'No suitable constructor was found for entity type 'ApplicationUser'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'genericRepositoryDepts' in 'ApplicationUser(IGenericRepository<Departments> genericRepositoryDepts)'.'
Which I think is telling me that the DI container is not recognising ApplicationUser as being 'DI-enabled' and therefore leaving EF to try and match the constructor to entities in the DB. Does this mean I just can't DI into ApplicationUser like this?