0
votes

I have a simple .Net Core WPF/PRISM/Unity App, that has a Class like this:

public class MyClass : IMyClass
{
    public MyClass(string someMessage)
    {

    }
}

public interface IMyClass
{
}

In App.Xaml.cs I have the following:

    public partial class App : PrismApplication
{
    protected override Window CreateShell()
    {
        Container.GetContainer().AddExtension(new Diagnostic());
        return Container.Resolve<MainWindow>();
    }

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterSingleton<MainWindow>();

        containerRegistry.GetContainer().RegisterType(
            typeof(IMyClass), 
            typeof(MyClass), 
            "", 
            new TransientLifetimeManager(), 
            new InjectionConstructor("Some nice message"));
    }
}

But if I try to inject IMyClass...

    public partial class MainWindow : Window
{
    private readonly IMyClass myClass;

    public MainWindow(IMyClass myClass)
    {
        InitializeComponent();
        this.myClass = myClass;
    }

I get the following error:

Unity.ResolutionFailedException: 'The current type, WpfApp7.IMyClass, is an interface and cannot be constructed. Are you missing a type mapping?


Exception occurred while:

·resolving type: 'IMyClass' for parameter: 'myClass' on constructor: MainWindow(IMyClass myClass) ·resolving type: 'MainWindow'

I did an Console App - with no Prism - and did the same code, it just worked nicely.

2
When and how do you create MainWindow? I suppose you erroneously try to create it before your registration is done. - Haukinger
I create the MainWindow in the CreateShell method already. - ThomasE
As a side note, I should add that it's a bit dubious to inject stuff into a view. What stuff might a view have to do that requires a service to do so that is so closely coupled to the view that it cannot be done in the view model...? - Haukinger

2 Answers

0
votes

You should create the MainWindow in your CreateShell() method. This works:

public partial class App : PrismApplication
{
    protected override Window CreateShell()
    {
        return Container.Resolve<MainWindow>();
    }

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.GetContainer().RegisterType(
        typeof(IMyClass),
        typeof(MyClass),
        "",
        new TransientLifetimeManager(),
        new InjectionConstructor("Some nice message"));
    }
}

public class MyClass : IMyClass
{
    public MyClass(string s)
    {
        //...
    }
}
0
votes

I solved it..., using this generic method instead.

containerRegistry.GetContainer().RegisterType<IMyClass, MyClass>(new InjectionConstructor(new object[] { "Works Nicely" }));

Thanks for your time and effort.