Question

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.

Was it helpful?

Solution

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>();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top