Search code examples
c#interfacelazy-evaluationlazy-initialization

Lazy Initialization - Invalid arguments


I am coding a MVC 5 internet application, and am having some trouble with initializing a Lazy object.

Here is my code:

public Lazy<IGenericRepository<Account>> accounts;
public IGenericRepository<Account> accountsNotLazy;

I am wanting to initialize these two variables in the constructor call to the class.

Here is the constructor code;

public GenericMultipleRepository(DbContext dbContext)
{
    this.dbContext = dbContext;
    accounts = new Lazy<GenericRepository<Account>>(dbContext);
    accountsNotLazy = new GenericRepository<Account>(dbContext);
}

Can I please have some help with this code?

Thanks in advance.

EDIT

I am wanting the exact same initialization as the accountsNotLazy variable, but using Lazy loading. The accountsNotLazy variable is initializing correctly, how come the accounts is not? The only difference is the Lazy keyword.

These are the errors:

The best overloaded method match for 'System.Lazy>.Lazy(System.Func>)' has some invalid arguments

As well as:

cannot convert from 'System.Data.Entity.DbContext' to 'System.Func>'

Here is the GenericRepository class:

public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
    protected DbSet<TEntity> DbSet;

    private readonly DbContext _dbContext;

    public GenericRepository(DbContext dbContext)
    {
        _dbContext = dbContext;
        DbSet = _dbContext.Set<TEntity>();
    }

    public GenericRepository()
    {
    }

    public IQueryable<TEntity> GetAll()
    {
        return DbSet;
    }

    public async Task<TEntity> GetByIdAsync(int id)
    {
        return await DbSet.FindAsync(id);
    }

    public IQueryable<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate)
    {
        return DbSet.Where(predicate);
    }

    public async Task EditAsync(TEntity entity)
    {
        _dbContext.Entry(entity).State = EntityState.Modified;
        await _dbContext.SaveChangesAsync();
    }

    public async Task InsertAsync(TEntity entity)
    {

        DbSet.Add(entity);
        await _dbContext.SaveChangesAsync();
    }

    public async Task DeleteAsync(TEntity entity)
    {
        DbSet.Remove(entity);
        await _dbContext.SaveChangesAsync();
    }
}

Solution

  • As many have mentioned that you need to pass a Func<T>, but the expression suggested as the answer is incorrect.

    Initialize your accounts variable as follows -

    accounts = new Lazy<IGenericRepository<Account>>(() => new GenericRepository<Account>(dbContext));
    

    Do note that when you want to access your instance of GenericRepository lazily, you would need to access Value property of Lazy class.. like so - accounts.Value, which will be of type GenericRepository<Account>