Note: I am not planning to use the Entity Framework as it does NOT support async queries.
I am unable to figure out which approach would be better for the following scenario with Dependency Injection and SQL Connection Pooling.
SQL Server Connection Pooling (ADO.NET) MSDN article recommends to use using (sqlConn) since I don't take a hit on connection.Open() and connection.Close() with Connection Pooling enabled.
Technique 1:
Inject a SqlConnection dependency into my CustomerRepository class.
Use an instance per HTTP Request for the SqlConnection.
Call connection.Open() before it is injected into the CustomerRepository class.
Technique 2:
Only inject the Connection String into my CustomerRepository class.
Initialize using (SqlConnection) blocks in each of my CRUD methods?
Additional Things to Consider
I will be using async calls with my SqlCommand.BeginExecuteReader() for some SQL queries that takes about 2-4 seconds to execute.
In some special scenarios, I need to run 2-or-more parallel SQL query calls as well.
Please also keep in mind how the two techniques affect the coding style for IDisposable and using (connection) stuff.
Questions
Are there any differences between the two approaches given the fact that Connection Pooling is enabled?
Which technique should I use and why?
Code Sample for Technique 1:
// ------------------------------------------------------------
// Autofac Dependency Injection setup
// ------------------------------------------------------------
ContainerBuilder builder = new ContainerBuilder();
builder.Register(
c => {
var conn = new SqlConnection( "connectionString" );
conn.Open(); // open the connection ahead of time before injecting it into my CustomerRepository
return conn;
})
.Named("myNamedConnection", typeof(SqlConnection))
.InstancePerHttpRequest();
builder.Register(
c => {
new CustomerRepository(c.ResolveNamed<SqlConnection>("myNamedConnection")))
})
.As<ICustomerRepository>();
// ------------------------------------------------------------
// CustomerRepository
// ------------------------------------------------------------
public class CustomerRepository : ICustomerRepository, IDisposable
{
private SqlConnection conn;
private bool disposed;
public CustomerRepository(SqlConnection connection)
{
conn = connection;
disposed = false;
}
public Customer GetById(int id)
{
using (var cmd = conn.CreateCommand())
{
// code to retrieve Customer by id
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (conn != null)
{
conn.Dispose();
conn = null;
}
}
disposed = true;
}
}
}
Code Sample for Technique 2:
// ------------------------------------------------------------
// CustomerRepository
// ------------------------------------------------------------
public class CustomerRepository : ICustomerRepository
{
private readonly string strConn;
public CustomerRepository(string strConnection) // strConnection has Connection Pooling enabled
{
strConn = strConnection;
}
public Customer GetById(int id)
{
using (var conn = new SqlConnection(this.strConn))
{
using (var cmd = conn.CreateCommand())
{
// code to retrieve Customer by id
}
}
}
}
Thanks in advance for any thoughtful inputs :-)
Don't go for technique 1. Leaving the connection open for the complete request is not adviced: it should be closed as soon as possible, so don't leave it open for the complete request.
Don't go for technique 2. Injecting a connection string in each and every repository is cumbersome and if you are doing that, it seems to me that you are missing an abstraction, in your code. You probably don't want every repository create a new SqlConnection by itself.
You might be better of by injecting an IDatabase abstraction of some sort into your repositories. You can inject the connection string in your IDatabase implementation. This abstraction can have a BeginExecuteReader method or perhaps even some higher level abstraction.
Related
I'm working on a .NET Core 2.2 Console Application that hosts an IHostedService:
public class MqttClientHostedService : IHostedService, IDisposable
{
[...]
public MqttClientHostedService(
ILogger<MqttClientHostedService> logger,
IOptions<MqttClientConfiguration> mqttConfiguration,
IPositionService positionService)
{
this.logger = logger;
this.config = mqttConfiguration;
this.positionService = positionService;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
mqttClient = new MqttFactory().CreateMqttClient();
mqttClient.Connected += async (s, e) => await MqttClient_Connected(s, e);
mqttClient.ApplicationMessageReceived +=
async (s, e) => await MqttClient_ApplicationMessageReceived(s, e);
await mqttClient.ConnectAsync(
new MqttClientOptionsBuilder()
.WithTcpServer(config.Value.Host, config.Value.Port).Build());
}
private async Task MqttClient_ApplicationMessageReceived(
object sender, MqttApplicationMessageReceivedEventArgs e)
{
string message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
await positionService.HandleMessage(message);
}
[...]
}
This IPositionService is a manager that inspects the message and checks if it can be saved inside our database:
public class PositionService : IPositionService
{
[...]
public PositionService(
IUnitOfWork unitOfWork, ILogger<PositionService> logger)
{
this.unitOfWork = unitOfWork;
this.logger = logger;
}
public async Task HandleMessage(string message)
{
Entity entity = await unitOfWork.EntityRepository.GetByMessage(message);
[...]
await unitOfWork.EntityRepository.UpdateAsync(entity);
await unitOfWork.Save();
}
[...]
}
IUnitOfWork is a wrapper around Entity Framework Core DbContext (please don't judge me, I have reasons to do this):
public class UnitOfWork : IUnitOfWork
{
[...]
public UnitOfWork(MyContext myContext)
{
this.myContext = myContext;
EntityRepository = new EFRepository<Entity>(myContext);
}
public async Task Save()
{
await myContext.SaveChangesAsync();
}
}
EFRepository<T>, that implements IRepository<T> interface, is a wrapper around DbSet<T> (again, please don't judge me). No relevant code here.
Console Application's Program.cs is configured like that:
[...]
.ConfigureServices((hostContext, services) =>
{
services.AddDbContext<MyContext>(
c => c.UseSqlServer("[...]", options => options.UseNetTopologySuite()),
ServiceLifetime.Transient);
services.AddTransient<IPositionService, PositionService>();
services.AddTransient(typeof(IRepository<>), typeof(EFRepository<>));
services.AddTransient<IUnitOfWork, UnitOfWork>();
services.AddHostedService<MqttClientHostedService>();
[...]
});
Problem is that PositionService.HandleMessage is being called many times per second, and being that DbContext is not thread safe I get this error message:
A second operation started on this context before a previous operation
completed.
I solved this issue by removing IUnitOfWork from PositionService's dependencies, injecting instead an IServiceScopeFactory, and doing:
using (IServiceScope serviceScope = serviceScopeFactory.CreateScope())
{
IUnitOfWork unitOfWork = serviceScope.ServiceProvider.GetService<IUnitOfWork>();
[...]
}
This way works, but I don't like it. It seems like a trick, and I don't like the fact that my PositionService knows about Dependency Injection and has to deal with scopes.
My question is: there's a better way to solve this problem without touching my classes? Should I make the whole UnitOfWork thread safe? Or maybe create it by hand without using DI?
The source of the problem is that MyContext is held captive as a Captive Dependency in the following object graph:
MqttClientHostedService
-> PositionService
-> UnitOfWork
-> MyContext
All types in this graph are registered as Transient, but still, services that act as hosted service (e.g. your MqttClientHostedService) are resolved only once for the duration of the application and cached indefinately. This effectively makes them a singleton.
In other words, MyContext is accidentally kept alive by the single MqttClientHostedService and because multiple messages can come in in parallel, you have yourself a race condition.
The solution is to let each ApplicationMessageReceived event run in its own unique little bubble (a scope) and resolve a new IPositionService from within that bubble. For instance:
public class MqttClientHostedService : IHostedService, IDisposable
{
[...]
public MqttClientHostedService(
ILogger<MqttClientHostedService> logger,
IOptions<MqttClientConfiguration> mqttConfiguration,
IServiceProvider provider)
{
this.logger = logger;
this.config = mqttConfiguration;
this.provider = provider;
}
[...]
private async Task MqttClient_ApplicationMessageReceived(
object sender, MqttApplicationMessageReceivedEventArgs e)
{
using (var scope = provider.CreateScope())
{
positionService = scope.ServiceProvider
.GetRequiredService<IPositionService>();
string message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
await positionService.HandleMessage(message);
}
}
[...]
}
I'd like to intercept var context = new MyDbContext() to return a different constructor call instead.
The great thing about EFfort is that it let's you set up an easy in-memory database for unit testing.
var connection = Effort.DbConnectionFactory.CreateTransient();
var testContext = new MyDbContext(connection);
But then you'd have to inject that context into your repository.
public FooRepository(MyDbContext context) { _context = context; }
Is it possible to just intercept var context = new MyDbContext() , so that it returns the testContext?
using (var context = new MyDbContext()) {
// this way, my code isn't polluted with a ctor just for testing
}
You have two possible options. Using factories or via Aspect oriented programming (like PostSharp)
referencing this article: http://www.progware.org/Blog/post/Interception-and-Interceptors-in-C-(Aspect-oriented-programming).aspx
Using PostSharp (AOP)
PostSharp is a great tool and can achieve the most clean interception
possible (meaning no changes in your classes and object generation at
all even if you do not your factories for object creation and/or
interfaces) but it is not a free library. Rather than creating proxies
at runtime, it injects code at compile time and therefore changes your
initial program in a seamless way to add method interception.
.....
The cool thing in this is that you do not change anything else in your
code, so your object can be still generated using the new keyword.
Using DI and Factory-pattern
I personally prefer the factory-pattern approach, but you seem apposed to having to inject any dependencies into your classes.
public interface IDbContextFactory<T> where T : DbContext {
T Create();
}
public class TestDbContextFactory : IDbContextFactory<MyDbContext> {
public MyDbContext Create() {
var connection = Effort.DbConnectionFactory.CreateTransient();
var testContext = new MyDbContext(connection);
return testContext;
}
}
public class FooRepository {
MyDbContext _context;
public FooRepository(IDbContextFactory<MyDbContext> factory) {
_context = factory.Create();
}
}
(edit: I just realized this isn't actually returning the other ctor call. working on it.)
Figured it out. Simple enough if you know how to do it:
[TestMethod]
public void Should_have_a_name_like_this()
{
// Arrange
var connection = Effort.DbConnectionFactory.CreateTransient();
ShimSolrDbContext.Constructor = context => new SolrDbContext(connection);
// Act
// Assert
}
And as usual, EFfort requires this constructor in the DbContext class:
public class SomeDbContext
{
public SomeDbContext() : base("name=Prod")
{
}
// EFfort unit testing ctor
public SomeDbContext(DbConnection connection) : base(connection, contextOwnsConnection: true) {
Database.SetInitializer<SolrDbContext>(null);
}
}
But it means the repo is blissfully unaware of the special Transient connection:
public class SomeRepository
{
public void SomeMethodName()
{
using (var context = new SomeDbContext())
{
// self-contained in repository, no special params
// and still calls the special test constructor
}
}
}
I am running into an issue where I can't figure out how to properly dispose of my object context I am creating every time I instantiate a new object.
public class OrderBLL{
var _iOrderLineDal;
public OrderBLL(){
_iOderLineDal = new OrderLineDal(new entityOBject(dbconnectionstring);
}
public OrderBLL(iOrderLineDal mockOrderLineDal){
_iOrderLineDal = mockOrderLineDal;
}
}
So the problem is, that every 30 seconds my service creates a new instance of the OrderBLL and then runs a method to see if there are any new orders in the Data base.
So every 30 seconds I create a new entityObject that is not being disposed of. the old implementation of the code was written using the using statement.
public bool HasNewOrders(){
using(var entityObject = new entityObject(dbconnectionString)){
var newOrders = entityObject.GetNewOrders();
}
//some logic
}
The problem with using this using statement is I cannot mock out the entityObject and easily write unit tests on any methods inside this OrderBLL class.
I tried disposing of it with a dispose method inside the OrderLineDal and once i got the data called dispose. That worked well the first iteration but the following iterations, the next 30 seconds, it would say that the entityObject was disposed of and cannot be used. (doesn't make sense to me, since I am creating a new one every time?)
Is there a way I can implement this repository pattern and still dispose of all the new entityObjects so I can mock the DAL out for unit testing?
I am working with EF 4. and it was not set up Code First, so I do not have POCO.
Ideally you would want to create your context outside of your OrderBLL (search google for Repository pattern).
public class OrderRepository : IOrderRepository, IDisposable
{
private readonly IOrderDBContext _dbContext;
// poor mans dependency injection
public OrderRepository() : this(new OrderDbContext("YourConnectionString")
{}
public OrderRepository(IOrderDBContext dbContext)
{
if (dbContext == null) throw new ArgumentNullException("dbContext");
_dbContext = dbContext;
}
public bool GetNewOrders(){
return _dbContext.Orders.Where(o => o.IsNew==true);
}
public void Dispose()
{
if (_dbContext != null) _dbContext.dispose();
}
}
public class OrderBLL : IOrderBLL
{
private readonly IOrderRepository _repository;
public OrderRepository(IOrderRepository repository)
{
if (repository == null) throw new ArgumentNullException("dbContext");
_repository = repository;
}
public bool HasNewOrders(){
var newOrders = _repository.GetNewOrders();
if (newOrders==null) return false;
return newOrders.Count() > 0;
}
}
[Test]
public void HasNewOrders_GivenNoNNewOrdersRetunedFromRepo_ReturnsFalse()
{
// test using nunit and nsubstitute
// Arrange
var repository = Substitue.For<IOrderRepository>();
var emptyOrderList = new List<Order>();
repository.GetNewOrders().Returns();
var orderBLL = new OrderBLL(repository);
// Act
var result = orderBLL.HasNewOrders();
// Assert
Assert.Equals(false, result);
}
Now you can inject your context into this class and easily test your business logic. Eventually you will need to create your dbContext and should also always expose this. I would suggest having a look at a DI container like Castle Windsor to manage the life of your objects, although in a service you may just want to manually create and dispose your context as close to the code entry point as possible (e.g. in the main method)
I'm using StructureMap to resolve references to my repository class. My repository interface implements IDisposable, e.g.
public interface IMyRepository : IDisposable
{
SomeClass GetById(int id);
}
An implementation of the interface using Entity Framework:
public MyRepository : IMyRepository
{
private MyDbContext _dbContext;
public MyDbContext()
{
_dbContext = new MyDbContext();
}
public SomeClass GetById(int id)
{
var query = from x in _dbContext
where x.Id = id
select x;
return x.FirstOrDefault();
}
public void Dispose()
{
_dbContext.Dispose();
}
}
Anyway as mentioned I'm using StructureMap to resolve IMyRepository. So when, where and how should I call my dispose method?
WARNING: please note that my views have changed, and you should consider the following advise outdated. Please see this answer for an updated view: https://stackoverflow.com/a/30287923/264697
While DI frameworks can manage lifetime of objects for you and some could even dispose objects for you after you're done using with them, it makes object disposal just too implicit. The IDisposable interface is created because there was the need of deterministic clean-up of resources. Therefore, in the context of DI, I personally like to make this clean-up very explicit. When you make it explicit, you've got basically two options: 1. Configure the DI to return transient objects and dispose these objects yourself. 2. Configure a factory and instruct the factory to create new instances.
I favor the second approach over the first, because especially when doing Dependency Injection, your code isn't as clean as it could be. Look for instance at this code:
public sealed class Client : IDisposable
{
private readonly IDependency dependency;
public Client(IDependency dependency)
{
this. dependency = dependency;
}
public void Do()
{
this.dependency.DoSomething();
}
public Dispose()
{
this.dependency.Dispose();
}
}
While this code explicitly disposes the dependency, it could raise some eyebrows to readers, because resources should normally only be disposed by the owner of the resource. Apparently, the Client became the owner of the resource, when it was injected.
Because of this, I favor the use of a factory. Look for instance at this example:
public sealed class Client
{
private readonly IDependencyFactory factory;
public Client(IDependencyFactory factory)
{
this.factory = factory;
}
public void Do()
{
using (var dependency = this.factory.CreateNew())
{
dependency.DoSomething();
}
}
}
This example has the exact same behavior as the previous example, but see how the Client class doesn't have to implement IDisposable anymore, because it creates and disposes the resource within the Do method.
Injecting a factory is the most explicit way (the path of least surprise) to do this. That's why I prefer this style. Downside of this is that you often need to define more classes (for your factories), but I personally don't mind.
RPM1984 asked for a more concrete example.
I would not have the repository implement IDisposable, but have a Unit of Work that implements IDisposable, controls/contains repositories and have a factory that knows how to create new unit of works. With that in mind, the above code would look like this:
public sealed class Client
{
private readonly INorthwindUnitOfWorkFactory factory;
public Client(INorthwindUnitOfWorkFactory factory)
{
this.factory = factory;
}
public void Do()
{
using (NorthwindUnitOfWork db =
this.factory.CreateNew())
{
// 'Customers' is a repository.
var customer = db.Customers.GetById(1);
customer.Name = ".NET Junkie";
db.SubmitChanges();
}
}
}
In the design I use, and have described here, I use a concrete NorthwindUnitOfWork class that wraps an IDataMapper that is the gateway to the underlying LINQ provider (such as LINQ to SQL or Entity Framework). In sumary, the design is as follows:
An INorthwindUnitOfWorkFactory is injected in a client.
The particular implementation of that factory creates a concrete NorthwindUnitOfWork class and injects a O/RM specific IDataMapper class into it.
The NorthwindUnitOfWork is in fact a type-safe wrapper around the IDataMapper and the NorthwindUnitOfWork requests the IDataMapper for repositories and forwards requests to submit changes and dispose to the mapper.
The IDataMapper returns Repository<T> classes and a repository implements IQueryable<T> to allow the client to use LINQ over the repository.
The specific implementation of the IDataMapper holds a reference to the O/RM specific unit of work (for instance EF's ObjectContext). For that reason the IDataMapper must implement IDisposable.
This results in the following design:
public interface INorthwindUnitOfWorkFactory
{
NorthwindUnitOfWork CreateNew();
}
public interface IDataMapper : IDisposable
{
Repository<T> GetRepository<T>() where T : class;
void Save();
}
public abstract class Repository<T> : IQueryable<T>
where T : class
{
private readonly IQueryable<T> query;
protected Repository(IQueryable<T> query)
{
this.query = query;
}
public abstract void InsertOnSubmit(T entity);
public abstract void DeleteOnSubmit(T entity);
// IQueryable<T> members omitted.
}
The NorthwindUnitOfWork is a concrete class that contains properties to specific repositories, such as Customers, Orders, etc:
public sealed class NorthwindUnitOfWork : IDisposable
{
private readonly IDataMapper mapper;
public NorthwindUnitOfWork(IDataMapper mapper)
{
this.mapper = mapper;
}
// Repository properties here:
public Repository<Customer> Customers
{
get { return this.mapper.GetRepository<Customer>(); }
}
public void Dispose()
{
this.mapper.Dispose();
}
}
What's left is an concrete implementation of the INorthwindUnitOfWorkFactory and a concrete implementation of the IDataMapper. Here's one for Entity Framework:
public class EntityFrameworkNorthwindUnitOfWorkFactory
: INorthwindUnitOfWorkFactory
{
public NorthwindUnitOfWork CreateNew()
{
var db = new ObjectContext("name=NorthwindEntities");
db.DefaultContainerName = "NorthwindEntities";
var mapper = new EntityFrameworkDataMapper(db);
return new NorthwindUnitOfWork(mapper);
}
}
And the EntityFrameworkDataMapper:
public sealed class EntityFrameworkDataMapper : IDataMapper
{
private readonly ObjectContext context;
public EntityFrameworkDataMapper(ObjectContext context)
{
this.context = context;
}
public void Save()
{
this.context.SaveChanges();
}
public void Dispose()
{
this.context.Dispose();
}
public Repository<T> GetRepository<T>() where T : class
{
string setName = this.GetEntitySetName<T>();
var query = this.context.CreateQuery<T>(setName);
return new EntityRepository<T>(query, setName);
}
private string GetEntitySetName<T>()
{
EntityContainer container =
this.context.MetadataWorkspace.GetEntityContainer(
this.context.DefaultContainerName, DataSpace.CSpace);
return (
from item in container.BaseEntitySets
where item.ElementType.Name == typeof(T).Name
select item.Name).First();
}
private sealed class EntityRepository<T>
: Repository<T> where T : class
{
private readonly ObjectQuery<T> query;
private readonly string entitySetName;
public EntityRepository(ObjectQuery<T> query,
string entitySetName) : base(query)
{
this.query = query;
this.entitySetName = entitySetName;
}
public override void InsertOnSubmit(T entity)
{
this.query.Context.AddObject(entitySetName, entity);
}
public override void DeleteOnSubmit(T entity)
{
this.query.Context.DeleteObject(entity);
}
}
}
You can find more information about this model here.
UPDATE December 2012
This an an update written two years after my original answer. The last two years much has changed in the way I try to design the systems I'm working on. Although it has suited me in the past, I don't like to use the factory approach anymore when dealing with the Unit of Work pattern. Instead I simply inject a Unit of Work instance into consumers directly. Whether this design is feasibly for you however, depends a lot on the way your system is designed. If you want to read more about this, please take a look at this newer Stackoverflow answer of mine: One DbContext per web request…why?
If you want to get it right, i'd advise on a couple of changes:
1 - Don't have private instances of the data context in the repository. If your working with multiple repositories then you'll end up with multiple contexts.
2 - To solve the above - wrap the context in a Unit of Work. Pass the unit of work to the Repositories via the ctor: public MyRepository(IUnitOfWork uow)
3 - Make the Unit of Work implement IDisposable. The Unit of Work should be "newed up" when a request begins, and therefore should be disposed when the request finishes. The Repository should not implement IDisposable, as it is not directly working with resources - it is simply mitigating them. The DataContext / Unit of Work should implement IDispoable.
4 - Assuming you are using a web application, you do not need to explicitly call dispose - i repeat, you do not need to explicitly call your dispose method. StructureMap has a method called HttpContextBuildPolicy.DisposeAndClearAll();. What this does is invoke the "Dispose" method on any HTTP-scoped objects that implement IDisposable. Stick this call in Application_EndRequest (Global.asax). Also - i believe there is an updated method, called ReleaseAllHttpScopedObjects or something - can't remember the name.
Instead of adding Dispose to IMyRepository, you could declare IMyRepository like this:
public interface IMyRepository: IDisposable
{
SomeClass GetById(int id);
}
This way, you ensure all repository will call Dispose sometimes, and you can use the C# "using" pattern on a Repository object:
using (IMyRepository rep = GetMyRepository(...))
{
... do some work with rep
}
In my application I am making use of Spring.Net for IoC. The service objects are called from the ASP.Net files to perform CRUD operations using these service object. For example, I have CustomerService to do all CRUD operations on Customer table. I use entity framework and the entities are injected .. my question is where do I call the dispose method?
As far as I understood from the API documentations, unless I call Dispose() there is no guaranty it will be garbage collected! So where and how do I do it?
Example Service Class:
public class CustomerService
{
public ecommEntities entities = {get; set;}
public bool AddCustomer(Customer customer)
{
try
{
entities.AddToCustomer(customer);
entities.SaveChanges();
return true;
}
catch (Exception e)
{
log.Error("Error occured during creation of new customer: " + e.Message + e.StackTrace);
return false;
}
}
public bool UpdateCustomer(Customer customer)
{
entities.SaveChanges();
return true;
}
public bool DeleteCustomer(Customer customer)
.
.
.
And I just create an object of CustomerService at the ASP partial class and call the necessary methods.
Thanks in advance for the best practice and ideas..
Regards,
Abdel Raoof
I have HttpModule in my application, which takes care of creating and disposing of context:
public class MyEntitiesHttpModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += ApplicationBeginRequest;
application.EndRequest += ApplicationEndRequest;
}
private void ApplicationEndRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Items[#"MyEntities"] != null)
((MyEntities)HttpContext.Current.Items[#"MyEntities"]).Dispose();
}
private static void ApplicationBeginRequest(Object source, EventArgs e)
{
//TextWriter logFile = File.CreateText(HttpContext.Current.Server.MapPath("~/sqllogfile.txt"));
var context = new MyEntities();
//context.Log = logFile;
HttpContext.Current.Items[#"MyEntities"] = context;
}
}
It creates it at the beginning of request and disposes at the end. Context is taken from HttpContext.Current.Items by Ninject and injected into my service object. I don't know how exactly it works with Spring.Net and what is your approach to creating ObjectContext, but I hope this answer will help. If Sprint.Net supports per request lifetime and doesn't need any modules, it propably takes care of disposing too. In other case, you can do it like here.
#LukLed is generally correct (+1) that the HTTP request is the correct scope. However, I very much doubt explicit code is required to call Dispose() with either NInject or Spring.Net as both of these should already be disposing instances they manage. HttpContext.Current is as good a place to store the reference as anything.
However, you (#Abdel) are wrong to say:
As far as I understood from the API documentations, unless I call Dispose() there is no guaranty it will be garbage collected!
This is just not right. Dispose() makes the collection somewhat more optimal and provides for deterministic release of unmanaged resources (e.g., your DB connection). But everything will eventually be collected, with or without calling Dispose().