We recently ran into the same issue and I think the problem is creating the SqlCommand
locally via calling it's constructor. When then assigning the connection to it it tries to clone the connection locally as well which fails due to some internal properties which are not available through remoting.
The workaround which did the trick for us was to call CreateCommand()
on the connection like this
void MethodRunningInAppDomainB(SqlConnection connectionFromAppDomainA, SqlTransaction transactionFromAppDomainA)
{
using (var cmd = connectionFromAppDomainA.CreateCommand())
{
cmd.CommandText = "this is my query";
cmd.Transaction = transaction;
cmd.Parameters.Add(...);
...
cmd.ExecuteNonQuery();
}
}
Bascially the connection and the transaction came from the main app which got passed to the plugin which is running in a different AppDomain (so it can be unloaded) which could execute some custom commands in the context of the main query.
My suspicion is that calling CreateCommand()
on the connection remotes the call back and creates the command in the same app domain as the connection lives in and the created command you get back is probably a proxy to that and that's why this way works.
Not sure if my explanation of the problem is 100% correct but it sounds somewhat logical to me and in any case it resolved the problem for us.