开发者

Prism + MEF: How to properly load in arguments into one of my services?

Basically I have the following scenario:

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 : MefBootst开发者_如何学JAVArapper
{
    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; }
}

How do I load x and y into my service properly? Also, how do I ensure that when doing this it doesn't collide with anything else in my Container or the such?


You don't have to use the StartupEventArgs. Your FooBarService could simply use Environment.GetCommandLineArgs like this:

[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: I'm not sure if args[0] is the first parameter or the program call, you have to try that out and in that case switch indexes one further!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜