我试图重构一段代码,并用尽了我能想到的选项。如何实例化一个COM类接口一般
这是原来的代码,我有:
if (WebConfigSettings.ComPartition == null && HttpContext.Current != null)
Nses = new NSession();
else
Nses = (INSession)Marshal.BindToMoniker(string.Format("partition:{0}/new:NuntioServer.NSession", WebConfigSettings.ComPartition));
和
if (WebConfigSettings.ComPartition == null && HttpContext.Current != null)
apses.Wses = new WSession();
else
apses.Wses = (IWSession)Marshal.BindToMoniker(string.Format("partition:{0}/new:NuntioServer.WSession", WebConfigSettings.ComPartition));
这是怎么我试图重构它:
(是的,在C#中,你可以instantiateaninterface)
public static TInterface Get<TSubInterface, TInterface>() where TSubInterface: TInterface
{
<snip></snip>
if (!useComPartitions)
return Activator.CreateInstance<TSubInterface>(); // --> this is not cooperating
return (TInterface)Marshal.BindToMoniker(.....);
}
这是我已经尝试过:
我试图指定新的()约束,然后做一个“新TSubInterface()”: 这将导致生成错误:” ..must是一个非抽象用公共无参数构造函数键入,以便将其用作通用类型或方法中的参数'TSubInterface'。“
当我使用Activator.CreateInstance时,我得到一个运行时异常:”无法创建一个实例接口“
当我使用Activator.CreateComInstanceFrom(”someAssemblyName“,”t ypeName“),我得到一个编译错误:‘不能转换表达式类型‘System.Runtime.Remoting.ObjectHandle’返回类型TInterface’
[编辑]我是能够使加入该编译'在哪里TSubInterface:class,但我不确定这是否合理,因为TSubInterface是一个接口。
使用CreateComInstanceFrom也不起作用,因为它试图找到在dll不是并且不应该是的目录中指定的程序集。
我可以以某种方式使这个编译和运行?
你使用这个方法的哪个代码? –
nses = COMUtils.Get() NSession和INSession都是接口。 –
TweeZz
你想让它工作只是因为你可以或者你打算在生产代码中使用它?如果另外一个人能够通过控制容器的反转来达到类似的目的,那么他们会更好。 – Rafal