I want to know, what is the best way to dispose the all IDisposable object after the request done.
AddTransient<T>- adds a type that is created again each time it's requested.AddScoped<T>- adds a type that is kept for the scope of the request.AddSingleton<T>- adds a type when it's first requested and keeps hold of it.
So, singleton could not be a good choice because it will disposes after app shot down. but scope and transient are good candidates. I have a repository which I want to create a connection with my db like this:
public class Dapperr : IDapper
{
private readonly IConfiguration _config;
private string Connectionstring = "DefaultConnection";
public Dapperr(IConfiguration config)
{
_config = config;
}
public void Dispose()
{
}
public T Get<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.Text)
{
using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));
return db.Query<T>(sp, parms, commandType: commandType).FirstOrDefault();
}
public List<T> GetAll<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)
{
using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));
return db.Query<T>(sp, parms, commandType: commandType).ToList();
}
}
Now In my start up I'm going to add dependency injection:
services.AddScoped<IDapper, Dapperr>();
I want to know if I am allow to remove All those using scop because of adding scope dependency. for example like this:
public class Dapperr : IDapper
{
private readonly IConfiguration _config;
private string Connectionstring = "DefaultConnection";
private readonly IDbConnection db ;
public Dapperr(IConfiguration config)
{
_config = config;
db = new SqlConnection(_config.GetConnectionString(Connectionstring));
}
public T Get<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.Text)
{
return db.Query<T>(sp, parms, commandType: commandType).FirstOrDefault();
}
public List<T> GetAll<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)
{
return db.Query<T>(sp, parms, commandType: commandType).ToList();
}
}
does the sql connection dispose after request ended or I still need to use using?