1

How do I inject constructor parameters in my dependencies that I configure using Prism?

I overrode RegisterTypes to register my dependencies like this:

public partial class App : PrismApplication
{
   protected override void RegisterTypes(IContainerRegistry containerRegistry)
   {
      containerRegistry.Register<IMyService, MyService>();        
   }
}

However, MyService has some constructor parameters that I need to be able to pass in. I want to be able to pass constructor parameters to MyService, similar to how I would do it like this in Unity.

containerRegistry.Register<IMyService, MyService>(
   new InjectionConstructor("param1", "param2"));
Ben Rubin
  • 6,909
  • 7
  • 35
  • 82

3 Answers3

3

I'd create a handcoded IMyServiceFactory. That can pass your parameters and potential dependencies of the service.

public interface IMyServiceFactory
{
    IMyService CreateMyService();
}

internal class MyServiceFactory : IMyServiceFactory
{
    public IMyService CreateMyService() => new MyService( "param1", "param2" );
}

Have a look at this answer, too.

Haukinger
  • 10,420
  • 2
  • 15
  • 28
  • Blegh, I was hoping there was a way to do this without factories, but I guess I'm out of luck. I like your suggestion of making the factory `internal`. Thanks for the answer. – Ben Rubin May 13 '20 at 12:56
  • 1
    Regarding the `internal` you can go even more hardcore and make the product a private class within the factory (if your testing requirements permit). – Haukinger May 13 '20 at 12:58
  • 1
    Regarding the factory in itself, see it as a clear sign for everyone that says "If you use this, the product is yours. It's your responsibility to dispose it when you're done with it." I've moved to injecting `Func` instead of `Something` (with transient lifetime) because it makes clear who disposes (the consumer or the container). – Haukinger May 13 '20 at 13:01
2

Another option is to register an instance:

containerRegistry.RegisterInstance<IMyService>(new MyService("param1", "param2"));

reference: Registering Types with Prism

Soleil
  • 6,404
  • 5
  • 41
  • 61
0

I have tested this and it works:

containerRegistry.Register<IMyService>(() => new MyService("param1", "param2"));
containerRegistry.RegisterSingleton<IMyService>(() => new MyService("param1", "param2"));

containerRegistry.Register(typeof(IMyService), () => new MyService("param1", "param2")); 
containerRegistry.RegisteSingleton(typeof(IMyService), () => new MyService("param1", "param2"));
user16217248
  • 3,119
  • 19
  • 19
  • 37
mbh
  • 7
  • 1