I have the following configured within my IContainer Initialize routine:
x.For<IDbConnection>().Use<SqlConnection>().Ctor<string>().Is(MY_SQL_CONNECTION_STRING);
Here’s the constructor for my service:
private readonly IForumRepository _repo;
public ForumService(IForumRepository repo)
{
_repo = repo;
}
And here’s the constructor for my repository:
private readonly IDbConnection _cn;
public ForumRepository(IDbConnection connection)
{
_cn = connection;
}
In one of my service routines, I am calling a method to get an object in my repository, then upon returning to the service layer I call a 2nd method in my repository – however, on this second call to the repository, my connection (_cn) no longer has a connection string associated with it (it appears to be wiped upon exiting the using {} block the first time my service called a method in the repository.
Here’s the first method that I call in the repository.
public Tag GetTag(int id)
{
Tag o;
const string q = @"select * from tags where id = @pId";
using (_cn)
{
_cn.Open();
o = _cn.Query<Tag>(q, new { pId = id }).SingleOrDefault();
} *** AT THIS POINT THE CONN STRING PROPERTY OF _CN IS CLEARED?!
return o;
}
I ‘d have thought this should work fine seeing as the constructor for my service instantiates a SQL Connection which the first call to the repo utilizes fine, and seeing as subsequent calls to my repo are in the same service scope I’d have thought that repository’s SqlConnection dependency should still retain the original connection string details.
Can someone please shed some light on where I’m going wrong with this?
After the
usingblock is finished, the object being used will be disposed. Does the connection string get removed on disposal? In any case, you likely shouldn’t use the object after is has been disposed.Based on the code in your post, I would think you don’t want to use the
usingblock? I think you will want to manually close the connection, though (I thinkusingwill do that automatically as part of disposal).