michael
michael

Reputation: 15302

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 : 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; }
}

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?

Upvotes: 2

Views: 538

Answers (1)

Markus H&#252;tter
Markus H&#252;tter

Reputation: 7906

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!

Upvotes: 1

Related Questions