怠zyインスタンスを初期化するときに、コンストラクターにパラメーターを渡す
-
10-10-2019 - |
質問
私が知っているように、変数が宣言されているかどうか Lazy
, 、そのコンストラクターは、私たちが使用するときに呼び出されます Value
財産。
これにいくつかのパラメーターを渡す必要があります Lazy
インスタンスですが、正しい構文を見つけることができません。これは私のデザインではありません、私はMEFを使用しています ExportFactory
, 、それは私を返します Lazy
私の部分のインスタンス。私の部品にはコンストラクターがあり、これらのコンストラクターをいくつかのパラメーターで呼び出す必要があります。
解決
MEFには、ExportFactoryで作成したときにコンストラクターパラメーターを部品に渡すための組み込みの方法がありません。 Wim Coenenが示唆していることのようなものは、おそらくあなたが望むものを達成するための最良の方法です。
他のヒント
あなたはあなた自身をエクスポートすることができます Func
代わりは:
public class FooFactory
{
[Export(typeof(Func<string,int,ExportLifetimeContext<IFoo>>))]
public ExportLifetimeContext<IFoo> CreateFoo(string param1, int param2)
{
Foo foo = new Foo(param1, param2);
return new ExportLifetimeContext<IFoo>(foo,
delegate
{
// Clean-up action code goes here. The client might not be able
// to do this through the IFoo interface because it might not
// even expose a Dispose method.
//
// If you created other hidden dependencies in order to construct
// Foo, you could also clean them up here.
foo.Dispose();
});
}
}
他の場所にインポートします:
[Export(typeof(ISomething))]
public class FooUser : ISomething
{
private readonly Func<string,int,ExportLifetimeContext<IFoo>> fooFactory;
[ImportingConstructor]
public FooUser(Func<string,int,ExportLifetimeContext<IFoo>> fooFactory)
{
this.fooFactory = fooFactory;
}
public void DoSomething()
{
using (var fooLifetime = this.fooFactory("hello", 3))
{
IFoo foo = fooLifetime.Value;
...
}
}
}
クリーンアップアクションが必要ない場合は、すべてを捨てることでこれをかなり単純化できます ExportLifetimeContext
もの。
ただし、のいくつかの実装 IFoo
他のものは使用できない(または他の使い捨てオブジェクトに依存する)可能性があります。したがって、最も正しいことは、「このオブジェクトで完了した」信号を抽象化に組み込むことです。 ExportLifetimeContext
提供します。
所属していません StackOverflow