How do I specify constructor parameters in my dependency injection container in Prism?

1.6k Views Asked by At

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"));
3

There are 3 best solutions below

3
Haukinger On BEST ANSWER

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.

0
Soleil On

Another option is to register an instance:

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

reference: Registering Types with Prism

0
mbh On

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"));