2

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.

4

1 回答 1

5

请参阅 IOC wiki 文档中的Autowire 注册部分。这只是注册一个单例实例,因为您传递的是现有实例,所以 IOC 无法控制类型的创建:

container.Register(new TodoRepository());

如果您希望它自动连接,则需要使用自动连接的 API 之一:

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));

或者您可以通过指定工厂方法手动控制实例的创建:

container.Register(c => new TodoRepository { 
    DbFactory = c.Resolve<IDbConnectionFactory>() 
});

如果您想注入一个,请IDbConnection确保它在RequestNone范围内:

container.Register<IDbConnection>(c => 
  c.Resolve<IDbConnectionFactory>().OpenDbConnection()
)
.ReusedWithin(ReuseScope.Request);
于 2013-07-01T16:25:41.800 回答