【发布时间】:2018-03-22 09:48:20
【问题描述】:
我做一个泛型并使用 DI
所以我创建了一个空类
public class DBRepo
{
}
和我的模型类继承类 DBRepo
public partial class UserAccount : DBRepo
{
public int Id { get; set; }
public string Account { get; set; }
public string Pwd { get; set; }
}
那么这是一个执行 CRUD 的接口
public interface IDBAction<TEntity> where TEntity : class,new()
{
void UpdateData(TEntity _entity);
void GetAllData(TEntity _entity);
}
public class DBService<TEntity> : IDBAction<TEntity> where TEntity : class,new()
{
private readonly CoreContext _db;
public DBService(CoreContext _db)
{
this._db = _db;
}
public void UpdateData(TEntity _entity)
{
this._db.Set<TEntity>().UpdateRange(_entity);
this._db.SaveChanges();
}
public void GetAllData(TEntity _entity)
{
var x = this._db.Set<TEntity>().Select(o => o).ToList();
}
}
我在构造函数中的依赖注入服务提供者
this.DBProvider = new ServiceCollection()
.AddScoped<IDBAction<DBRepo>, DBService<DBRepo>>()
.AddScoped<DBContext>()
.AddDbContext<CoreContext>(options => options.UseSqlServer(ConnectionString))
.BuildServiceProvider();
我获得服务的最后一步
DBProvider.GetService<IDBAction<DBRepo>>().GetAllData(new UserAccount());
我会收到与标题相同的错误消息
或者我改成
DBProvider.GetService<IDBAction<UserAccount>>().GetAllData(new UserAccount());
我会收到其他消息
对象引用未设置为对象的实例。'
但是 void UpdateData() 可以工作, 那么如何解决 GetAllData() 问题呢?
【问题讨论】:
标签: asp.net-core dependency-injection