Reputation: 1679
I want to access the database from a repository rather than the service class (for increased seperation - not sure if this is overkill tho) i.e.
public class TodoRepository // : BaseRepository derive the class and inject IDbConnection somehow?
{
public List<Todo> GetByIds(long[] ids)
{
return Db.Select<Todos>(t => Sql.In(t.id, ids)); <-- how to get 'Db' in here
}
}
The service base class already enables direct access to databases via ormlite using 'Db' object thus:
public class Service : IService, IRequiresRequestContext, IServiceBase, IResolver, IDisposable
{
public virtual IDbConnection Db { get; }
}
Leading me to believe I can do this perhaps so I can use 'Db' in derived classes:
public class BaseRepository: IDisposable
{
public virtual IDbConnection Db { get; }
}
My AppHost has this line in it to pass in the connection string and register the repository:
container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider));
container.Register(new TodoRepository());
How to inject or autowire up the IDbConnection to the BaseRepository class? I've already attempted registering and autowiring the BaseRepository in the AppHost with no luck.
Upvotes: 2
Views: 1866
Reputation: 143319
Please see the Autowire registration section in the IOC wiki docs. This just registers a singleton instance, since you're passing in an existing instance the IOC is not able to control the creation of the type:
container.Register(new TodoRepository());
If you want it auto-wired, you need to use one of the auto-wired APIs:
container.RegisterAutoWired<TodoRepository>();
container.RegisterAutoWiredAs<TodoRepository,ITodoRepository>();
container.RegisterAs<TodoRepository,ITodoRepository>(); //shorter alias
container.RegisterAutoWiredType(typeof(MyType));
container.RegisterAutoWiredType(typeof(MyType),typeof(IMyType));
container.RegisterAutoWiredTypes(typeof(MyType),typeof(MyType2),typeof(MyType3));
Or you can manually control the creation of your instance by specifying a factory method:
container.Register(c => new TodoRepository {
DbFactory = c.Resolve<IDbConnectionFactory>()
});
If you want to inject an IDbConnection
instead make sure it's in Request
or None
Scope:
container.Register<IDbConnection>(c =>
c.Resolve<IDbConnectionFactory>().OpenDbConnection()
)
.ReusedWithin(ReuseScope.Request);
Upvotes: 5