Search code examples
c#mvvmservice-locatorcatel

How to register an inheriting service with constructor parameters?


I have a parent abstract service, with its own interface.

public interface IParentService
{
    void ParentMethod(object parameter);
}

public abstract class ParentService : IParentService
{
    protected object _parameter;

    public void ParentMethod() {}

    public ParentService(object parameter)
    {
        _parameter = parameter;
    }
}

And I have n services inheriting it, looking like this:

public interface INthChildService
{
    void NthChildMethod();
}

public class NthChildService : ParentService, INthChildService
{
    public void NthChildMethod() {}

    public NthChildService(object parameter) : base(parameter) {}
}

How can I register their types in the service locator while keeping the constructor parameter? Is it possible?

Here's what I tried with no success, giving me the TypeNotRegisteredException : 'MyNamespace.INthChildService' is not registered or could not be constructed:

var serviceLocator = ServiceLocator.Default;
serviceLocator.RegisterType<IParentService, ParentService>();
serviceLocator.RegisterType<INthChildService, NthChildService>();

Solution

  • Introduction to the ServiceLocator, chapter Registering an instance of a type.

    When a service has constructor parameters, you have to manually register an instance instead of just registering its type. This way you can pass the required parameters to the RegisterInstance method.

    There's no need to register the parent service whatsoever in my case, since it's abstract and thus won't ever be injected anywhere.

    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            object parameter = new object();
            ServiceLocator.Default.
                RegisterInstance<INthChildService>(new NthChildService(parameter));
        }
    }