Assembly.CreateInstance を通じてロードされる C# プラグインに引数を渡すにはどうすればよいですか?
-
02-07-2019 - |
質問
私が今持っているもの(プラグインが正常にロードされたもの)は次のとおりです。
Assembly myDLL = Assembly.LoadFrom("my.dll");
IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass;
これは、引数のないコンストラクターを持つクラスでのみ機能します。コンストラクターに引数を渡すにはどうすればよいですか?
解決
あなたはできません。代わりに使用してください Activator.CreateInstance 以下の例に示すように (クライアント名前空間は 1 つの DLL にあり、ホストは別の DLL にあることに注意してください。コードが機能するには、両方が同じディレクトリに存在する必要があります。)
ただし、本当にプラグイン可能なインターフェイスを作成したい場合は、コンストラクターに依存するのではなく、インターフェイスで指定されたパラメーターを受け取る Initialize メソッドを使用することをお勧めします。そうすれば、プラグイン クラスがコンストラクターで受け入れられたパラメーターを受け入れることを「期待」するのではなく、プラグイン クラスがインターフェイスを実装することを要求するだけで済みます。
using System;
using Host;
namespace Client
{
public class MyClass : IMyInterface
{
public int _id;
public string _name;
public MyClass(int id,
string name)
{
_id = id;
_name = name;
}
public string GetOutput()
{
return String.Format("{0} - {1}", _id, _name);
}
}
}
namespace Host
{
public interface IMyInterface
{
string GetOutput();
}
}
using System;
using System.Reflection;
namespace Host
{
internal class Program
{
private static void Main()
{
//These two would be read in some configuration
const string dllName = "Client.dll";
const string className = "Client.MyClass";
try
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
Type classType = pluginAssembly.GetType(className);
var plugin = (IMyInterface) Activator.CreateInstance(classType,
42, "Adams");
if (plugin == null)
throw new ApplicationException("Plugin not correctly configured");
Console.WriteLine(plugin.GetOutput());
}
catch (Exception e)
{
Console.Error.WriteLine(e.ToString());
}
}
}
}
他のヒント
電話
public object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)
その代わり。MSDN ドキュメント
編集:これを否決する場合は、なぜこのアプローチが間違っているのか、あるいは最善の方法ではないのかについて洞察を与えてください。
でできます Activator.CreateInstance
Activator.CreateInstance は、Type と、Types コンストラクターに渡したいものを受け取ります。
http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
また、パフォーマンスが向上する可能性がある Activator.CreateInstance も使用できません。以下の StackOverflow の質問を参照してください。