2011-03-08 11 views
2

基本的に私は次のシナリオを持っている:プリズム+ MEF:私のサービスに引数を適切に読み込むには?

App.xaml.cs:

protected override void OnStartup(StartupEventArgs e) 
{ 
    base.OnStartup(e); 

    string x = (e.Args.Length > 0) ? e.Args[0]; 
    string y = (e.Args.Length > 1) ? e.Args[1]; 

    Bootstrapper bootstrapper = new MyBootstrapper(x, y); 
    bootstrapper.Run(); 
} 

MyBootstrapper.cs:

public sealed class MyBootstrapper : MefBootstrapper 
{ 
    private string _x; 
    private string _y; 

    public MyBootstrapper(string x, string y) 
    { 
     _x = x; 
     _y = y; 
    } 

    protected override void ConfigureAggregateCatalog() 
    { 
     base.ConfigureAggregateCatalog(); 

     AggregateCatalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly())); 
    } 

    protected override DependencyObject CreateShell() 
    { 
     return Container.GetExportedValue<ClientShell>(); 
    } 

    protected override void InitializeShell() 
    { 
     base.InitializeShell(); 

     Application.Current.MainWindow = (Window)Shell; 
     Application.Current.MainWindow.Show(); 
    } 
} 

FooBarService.cs

public interface IFooBarService 
{ 
    string x { get; } 
    string y { get; } 
} 

[Export("FooBarService", typeof(IFooBarService))] 
public class FooBarService : IFooBarService 
{ 
    string x { get; protected set; } 
    string y { get; protected set; } 
} 

サービスにxとyを正しくロードするにはどうすればよいですか?また、これを実行するときにコンテナやそのようなものと衝突しないようにするにはどうすればよいですか?

答えて

1

StartupEventArgsを使用する必要はありません。

[Export("FooBarService", typeof(IFooBarService))] 
public class FooBarService : IFooBarService 
{ 
    public void FooBarService() 
    { 
     var args = Environment.GetCommandLineArgs(); 
     x = (args.Length > 0) ? args[0]:""; 
     y = (args.Length > 1) ? args[1]:""; 
    } 
    string x { get; protected set; } 
    string y { get; protected set; } 
} 

EDIT::私は、引数が[0]最初のパラメータまたはプログラム呼び出しであれば、あなたはそれを試してみると、その場合スイッチにする必要がわからないあなたのFooBarServiceは、単純にこのようなEnvironment.GetCommandLineArgsを使用することができますもう1つ索引を付ける!

+0

うーん、私はそれがそれを消費するアプリのコマンドラインを引き継ぐことが嫌い唯一のことを除いて、それは良いアイデアです。最初の2つの引数がこのサービス用に予約されているため、別のサービスが同じことを行った場合に衝突する可能性があります。じゃあ何? 2つのサービスは異なる理由でargsの同じ順序で戦っています。 – michael

+1

@michaelそれでは、ちょうど1レベル高い抽象化を行います。 argumentorderとstuffのすべての詳細を処理するCommandLineArgumentServiceを作成します。 –

関連する問題