For any object which lifetime must explicitly managed (such as objects that implement IDisposable
) or matters to the user, try not to inject them, but inject a factory that allows creating such objects instead. Define this interface for instance:
public interface IDbDataContextFactory
{
dbDataContext CreateNew();
}
And use it as follows:
public class SqlPupilBlockService
{
private IDbDataContextFactory contextFactory;
public SqlPupilBlockService(
IDbDataContextFactory contextFactory)
{
this.contextFactory = contextFactory;
}
public void DoSomeOperation()
{
using (var db = this.contextFactory.CreateNew())
{
// use the dbDataContext here.
}
}
}
An implementation of would be very simple, like this:
public class DbDataContextFactory : IDbDataContextFactory
{
public dbDataContext CreateNew()
{
return new dbDataContext();
}
}
And registration goes like this:
Bind<IDbDataContextFactory>().To<DbDataContextFactory>();
The use of a factory makes it very explicit who is the owner of the created object and who should control its lifetime. This makes your code more readable and follows the principle of least surprise.
UPDATE
More than a year has past since I submitted this answer. Instead of using factories, I now often inject the data context itself, and register it on a per (web) request basis. However; a shift in how you need to design your application might be needed, so as always: it depends. Please take a look at this answer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…