I’m running into this problem currently in my WCF service. “The timeout period elapsed prior to obtaining a connection from the pool”
Now I understand the error, my question is, what is the proper way to manage the Sql connection in a WCF service using Ninject.
What I have done is this.
In the binding I have
Bind<IConnectionFactory>().To<ConnectionFactory>().InScope(c => OperationContext.Current);
And my connection factory looks like this.
public class ConnectionFactory : IConnectionFactory
{
private string connectionString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;
private SqlConnection sqlConnection;
public SqlConnection GetOpenConnection()
{
if (sqlConnection == null)
sqlConnection = new SqlConnection(connectionString);
if (sqlConnection.State != ConnectionState.Open)
sqlConnection.Open();
return sqlConnection;
}
public void CloseConnection()
{
sqlConnection.Close();
}
Whenever I need a Sql connection I invoke it with via an IoC container like this.
SqlConnection connection = IoC.Resolve<IConnectionFactory>().GetOpenConnection();
My assumption was, that whenever I am dealing with the same request, I would get the same connection back from Ninject, and all connection calls within that request life time will get the same connection. Based on the error, I am assuming this is not happening. Is there a better way of doing this ? Or what is a better connection management paradigm for WCF with ninject ? I feel that making the connection factory a singleton would be the wrong way to go, but that’s just my gut feeling.
EDIT: I would like to add that I inject the connection into my repositories like this
private readonly SqlConnection connection;
public RandomRepository(IConnectionFactory connectionFactory)
{
connection = connectionFactory.GetOpenConnection();
}
Hy,
You can install Ninject.Extensions.WCF this provides you appropriate scoping for WCF services. Then you can inject an
SqlConnectiondirectly into your classes without having to use your connection factory. Simply use a method binding with the appropriate scope. For example with call scope:Ninject will then take care of disposing the connection when your request is out of scope.