dimanche 11 juillet 2021

Loading mongo with reflection - 'object' does not contain a definition for 'Description'?

We need to load mongodb c# assembly at runtime .

( reason: health check service attached to an app via nuget , needs to check the app for mongo connectivity, but it should use the existing(!) mongo dll in the BIN. Not bringing one of its own, Hence loading mongo by reflection)

All I need to check is this code :

  MongoClient client = new MongoClient(mongoConnection);
  var res = client.Cluster.Description.State == ClusterState.Connected;

I've managed to do the first part:

Assembly dll = Assembly.LoadFile(@"C:\Users\RoyiNamir\....\MongoDB.Driver.dll");
Type type = dll.GetType("MongoDB.Driver.MongoClient");
Console.WriteLine(type); //MongoDB.Driver.MongoClient

dynamic client = Activator.CreateInstance(type, mongoConnection);
Console.WriteLine(client.Cluster.Description );

I get an exception on the last line , where I try to print client.Cluster.Description :

enter image description here

Message
'object' does not contain a definition for 'Description' 

Source
Anonymously Hosted DynamicMethods Assembly 

StackTrace
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at UserQuery.Main()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart() 

But - if I execute Console.WriteLine(client.Cluster); instead , then I do get result :

SingleServerCluster

Using reflector, I see that Description is :

ClusterDescription Description { get; }

Where ClusterDescription is :

  public sealed class ClusterDescription : IEquatable<ClusterDescription> {}

Question:

Why does the exception is being thrown?
Using dynamic, How can I access the Description property?





Aucun commentaire:

Enregistrer un commentaire