延迟初始化 - 参数无效

时间:2014-12-28 04:26:28

标签: c# interface lazy-evaluation lazy-initialization

我正在编写MVC 5互联网应用程序,并且在初始化Lazy对象时遇到了一些麻烦。

这是我的代码:

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

我想在对类的构造函数调用中初始化这两个变量。

这是构造函数代码;

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

我可以帮助您使用此代码吗?

提前致谢。

修改

我想要与accountsNotLazy变量完全相同的初始化,但使用Lazy loadingaccountsNotLazy变量正在初始化,accounts怎么没有?唯一的区别是Lazy关键字。

这些是错误:

  

最佳重载方法匹配   &#39;&System.Lazy GT; .Lazy(System.Func&GT;)&#39;   有一些无效的论点

以及:

  

无法转换为System.Data.Entity.DbContext&#39;至   &#39;&System.Func GT;&#39;

这是GenericRepository类:

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();
    }
}

3 个答案:

答案 0 :(得分:1)

正如许多人提到的那样,您需要传递Func<T>,但建议的答案是不正确的。

按如下方式初始化accounts变量 -

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

请注意,当您想要访问GenericRepository lazily 的实例时,您需要访问Value类的Lazy属性..就像这样 - {{1 },类型为accounts.Value

答案 1 :(得分:0)

Lazy<T>的构造函数需要类型为Func<T>的参数。您可能想尝试这样做:

accounts = new Lazy<GenericRepository<Account>>(() => { return dbContext; });

答案 2 :(得分:0)

Lazy<T>类的构造函数是

Lazy<T>(Func<T>)

您可以将GenericMultipleRepository构造函数更改为:

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