3

インポートが機能していません-オブジェクトがnullです。元々はImportManyでしたが、問題を特定するためにImportに簡略化しましたが、うまくいきませんでした。

私はこのサイトとGoogleを調べて、主なアイデアに従いました。

  • クラスを自分でインスタンス化しないでください。MEFにインスタンス化させてください。そうしないと、container.getExport()を呼び出します-それでも機能しません
  • [Import]プロパティを含むクラスに[Export]を配置します。そうしないと、コンテナ構成プロセスによって一部として取得されません(デバッグ時に確認されます)。

私のコード設定は次のとおりです(コンパクトにするために簡略化されています)。

アセンブリ1

public class MyBootstrapper
{
    //Automatically called by ExcelDna library, I do not instantiate this class
    public void AutoOpen()
    {
        var ac1 = new AssemblyCatalog(typeof(XLHandler).Assembly);
        var ac2 = new AssemblyCatalog(typeof(MyComponent).Assembly);

        var agc = new AggregateCatalog();
        agc.Catalogs.Add(ac1);
        agc.Catalogs.Add(ac2);

        var cc = new CompositionContainer(agc);

        try
        {
            cc.ComposeParts(this);
        }
        catch (CompositionException exception) {}
    }
}

[Export]
public class XLHandler
{
    [Import(typeof(IMyComponent))]
    public IMyComponent _component;

    public void SomeMethod()
    {
        //try to use _component but it is null
    }
}

アセンブリ2

public interface IMyComponent
{
    //stuff...
}

アセンブリ3

[Export(typeof(IMyComponent)]
public MyComponent : IMyComponent
{
    //more stuff...
}

XLHandlerの_component変数がMEFコンテナによって注入されない理由を知っている/知っている人はいますか?

Assembly2のインターフェイスのAssemblyCatalogをエクスポート/作成する必要がありますか?

4

2 に答える 2

8

パーツをインポートするときは[Import]、プロパティで属性を使用するか、コンストラクターの一部として要求して属性を使用することができ[ImportingConstructor]ます。

[Import] 属性を使用してインポートされたパーツは、クラスのコンストラクターでは使用できません。

したがって、あなたの場合、次のXLHandlerようにクラスを変更します。

[Export]
public class XLHandler
{
    [ImportingConstructor]
    public void SomeMethod(MyComponent component)
    {
        _component = component;
       // You can use _component, since it has already been resolved...
    }
}
于 2013-03-02T22:55:10.933 に答える
2

交換MyBootstrapper.AutoOpenする必要があります:

cc.ComposeParts(this);

次のようなもので:

var handler = new XLHandler();
cc.ComposeParts(handler);

また:

var handler = cc.GetExportedValue<XLHandler>();

MyBootstrapper輸入品がないため、のパーツを作成することはできません。ComposeParts何もしません。

別のアプローチは、にインポートを追加することMyBootstrapperです。好き:

public class MyBootstrapper
{
    [Import]
    XLHandler XLHandler;

    //Automatically called by ExcelDna library, I do not instantiate this class
    public void AutoOpen()
    {
        //Leave your implementation unchanged.
    }
}

ちなみにMyComponentコンパイルしません。

于 2013-03-04T09:40:35.643 に答える