我有以下存储库类: public class RepositoryT : IDisposable where T : new(){ public IDbConnectionFactory DbFactory { get; set; } //Injected by IOC IDbConnection db; IDbConnection Db { get { return db ?? (db = DbFactory.Open()); } } p
public class Repository<T> : IDisposable where T : new() { public IDbConnectionFactory DbFactory { get; set; } //Injected by IOC IDbConnection db; IDbConnection Db { get { return db ?? (db = DbFactory.Open()); } } public Repository() { Db.DropAndCreateTable<T>(); } public List<T> GetByIds(long[] ids) { return Db.Ids<T>(ids).ToList(); } }
然后在我的AppHost.Configure()中.我像这样注册依赖:
container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(ConfigurationManager. ConnectionStrings["AppDb"].ConnectionString, SqlServerDialect.Provider)); container.RegisterAutoWired<Repository<Todo>>().ReusedWithin(Funq.ReuseScope.None);
但是当我运行我的应用程序时,似乎我的DbFactory为null并且没有正确注入,因为我得到了Null Reference异常.
尝试访问构造函数中的任何依赖项时它将为null,因为在IOC有机会注入任何依赖项之前启动了该类.我会将任何初始化/设置逻辑移出到AppHost.Configure()中,例如:
using (var db = container.Resolve<IDbConnectionFactory>().Open()) { db.DropAndCreateTable<MyType>(); }