2016-06-17 1 views
0

この投稿の分かりやすいタイトルの作成方法は不明でした。そのクラスが依存関係としているインタフェースの具体的な実装のためのクラスのインスタンスの作成

は、私はクラス

[Export(typeof(IMessageSender))] 
public class MessageSender : IMessageSender 
{ 
    private IMessagingInterface _messagingInterface; 
    private IEventAggregator _eventAggregator; 

    [ImportingConstructor] 
    public MessageSender(IMessagingInterface messagingInterface, IEventAggregator eventAggregator) 
    { 
     _messagingInterface = messagingInterface; 
     _eventAggregator = eventAggregator; 
    } 

    public void SendMessage(string message) 
    { 
     _messagingInterface.Write(message); 
    } 

    public InterfaceStatus GetStatus() 
    { 
     return _messagingInterface.Status; 
    } 

    ... 
    etc. Many methods in this class. 
} 

を持っていると私は、そのような自分のアプリケーションで

[Export(typeof(IMessagingInterface))] 
public SerialPortInterface : IMessagingInterface 
{ 
    .. 
} 

[Export(typeof(IMessagingInterface))] 
public UdpInterface : IMessagingInterface 
{ 
    .. 
} 
etc 

として、IMessagingInterfaceいくつかの異なるがあると、私は現在、自分のアプリケーションの起動時にこのようなさまざまな部分をインスタンス化:

eventAggregator = new EventAggregator(); 
batch.AddExportedValue<IMessageSender>("SerialPortSender", new MessageSender(new SerialPortInterface(), eventAggregator); 
batch.AddExportedValue<IMessageSender>("UdpSender", new MessageSender(new UdpInterface(), eventAggregator); 
... 
etc for the rest 

次に、私が指したいものを指定することができます契約名を使用して他の場所に影響を与えます。

しかし、私はブートストラップで自分自身でこのコンポジションを行い、newでインスタンスを作成するのは間違っていて不必要ですが、別のやり方ではありませんでした。

+0

IMessagingInterfaceの実装用にカタログを作成し、そのカタログについて知っているコンテナを使用して 'MessageSender'を作成してください。 MEFコンテナはインスタンス自体を管理します。 – Dennis

答えて

1

はこの記事を見ている: Getting all types that implement an interface

をそしてインスタンスを構築するためにActivator.CreateInstance(...)を使用します(参照:https://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx)をこのような

何かがそれを実行する必要があります。Tchiとして

eventAggregator = new EventAggregator(); 
var type = typeof(IMyInterface); 
var types = AppDomain.CurrentDomain.GetAssemblies() 
    .SelectMany(s => s.GetTypes()) 
    .Where(p => type.IsAssignableFrom(p)); 

foreach (var t in types) 
{ 
    var instance = (IMyInteface)Activator.CreateInstance(t); 
    batch.AddExportedValue<IMessageSender>(t.Name, new MessageSender(instance, eventAggregator); 
} 

Yuan氏は、IOCフレームワークを使用することも指摘しています。

これらはあなたがあなたが提供する構成に応じてのためのアセンブリおよびインスタンスの作成のスキャンを処理します。

1

これまで私はこの問題を抱えていましたが、私はMEFと結びついてMicrosoft Unityを使用した後、単体コンテナをMEF拡張/プラグインコンストラクタに渡すだけです。名前付き依存関係をUnityに登録して解決するのは簡単です。

関連する問題