I'm trying to refactor a piece of code and ran out of options I can think off.
This is the original code I had:
if (WebConfigSettings.ComPartition == null && HttpContext.Current != null)
Nses = new NSession();
else
Nses = (INSession)Marshal.BindToMoniker(string.Format("partition:{0}/new:NuntioServer.NSession", WebConfigSettings.ComPartition));
AND
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));
And this is how I'm trying to refactor it:
(Yes, in C# you can instantiate an interface.)
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(.....);
}
Here's what I already tried:
I tried specifying the new() constraint and then doing a 'new TSubInterface()': this results in a build error: "..must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TSubInterface' in the generic type or method.."
when I use Activator.CreateInstance, I get a runtime exception: "Cannot create an instance of an interface"
when I use Activator.CreateComInstanceFrom("someAssemblyName", "typeName"), I get a compilation error: "Cannot convert expression type 'System.Runtime.Remoting.ObjectHandle' to return type TInterface"
[edit] I was able to make this compile by adding 'where TSubInterface : class, but I'm not sure if that makes sense, since TSubInterface is an interface.
Using CreateComInstanceFrom also doesn't work, because it's trying to find the assembly which is specified in a directory where that dll is not and should not be.
Can I somehow make this compile and run?
Both NSession and INSession are interface
and you have a constraintNSession : INSession
. Are these really meant to be 2 interfaces where one inherits the other? If so, why is the name of the interface in templateTClass
. – DozyCreateInstance
overloads use the constructors of the specified type, without looking up the 'alias' class. However, I am interested in background of your decision to do it this way. It seems a very bad idea to me. – Dozy