Search code examples
c#wpfprismprism-7

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


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

Solution

  • 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.