首页 > 解决方案 > 使用反射加载程序集 - “对象”不包含“描述”的定义?

问题描述

我们需要在运行时加载 mongodb c# 程序集。

原因:通过 nuget 附加到应用程序的运行状况检查服务,需要检查应用程序的 mongo 连接性,但它应该使用 BIN 中现有的(!)mongo dll。没有自带一个,因此通过反射加载 mongo

我需要检查的是这段代码:

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

我已经成功完成了第一部分:

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 );

我在最后一行出现异常,我尝试打印client.Cluster.Description

在此处输入图像描述

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() 

但是 - 如果我 Console.WriteLine(client.Cluster);改为执行,那么我会得到结果:

单服务器集群

使用反射器,我看到描述是:

ClusterDescription Description { get; }

ClusterDescription在哪里:

  public sealed class ClusterDescription : IEquatable<ClusterDescription> {}

问题:

为什么会抛出异常?
使用动态/反射,我如何访问该Description属性?

标签: c#mongodbdynamicreflection

解决方案


这是因为该类Description显式地实现了该属性。因此,您的代码应该看起来像这样才能修复它。也就是说,您需要显式转换为正确的接口。

    dynamic c =Activator.CreateInstance(type);
    Console.WriteLine(((ICluster)c.Cluster).Description);

或者您可以使用如下所有动态:

 dynamic c =Activator.CreateInstance(type);
var targetType = type.GetProperties().Where(x => x.Name == "Cluster").Single().PropertyType;
Console.WriteLine(targetType.GetProperty("Description").GetValue(c.Cluster));

推荐阅读