I have the following repository class:
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();
}
}
Then in my AppHost.Configure()
. I register the dependency like so:
container.Register<IDbConnectionFactory>(c =>
new OrmLiteConnectionFactory(ConfigurationManager.
ConnectionStrings["AppDb"].ConnectionString, SqlServerDialect.Provider));
container.RegisterAutoWired<Repository<Todo>>().ReusedWithin(Funq.ReuseScope.None);
But when I run my application it seem's my DbFactory
is null and not being injected properly as I get a Null Reference exception.
It's going to be null when trying to access any dependency in the constructor because the class is initiated before the IOC has a chance to inject any of the dependencies.
I would move out any initialization/setup logic into AppHost.Configure()
, e.g:
using (var db = container.Resolve<IDbConnectionFactory>().Open())
{
db.DropAndCreateTable<MyType>();
}
来源:https://stackoverflow.com/questions/14486462/servicestack-dependency-seems-to-not-be-injected