我有一个父抽象服务,有自己的界面。
public interface IParentService
{
void ParentMethod(object parameter);
}
public abstract class ParentService : IParentService
{
protected object _parameter;
public void ParentMethod() {}
public ParentService(object parameter)
{
_parameter = parameter;
}
}
我继承了n
个服务,看起来像这样:
public interface INthChildService
{
void NthChildMethod();
}
public class NthChildService : ParentService, INthChildService
{
public void NthChildMethod() {}
public NthChildService(object parameter) : base(parameter) {}
}
如何在保留构造函数参数的同时在服务定位器中注册其类型?有可能吗?
这是我尝试过但没有成功,给我TypeNotRegisteredException : 'MyNamespace.INthChildService' is not registered or could not be constructed
:
var serviceLocator = ServiceLocator.Default;
serviceLocator.RegisterType<IParentService, ParentService>();
serviceLocator.RegisterType<INthChildService, NthChildService>();
答案 0 :(得分:1)
Introduction to the ServiceLocator,章节注册类型的实例。
当服务具有构造函数参数时,您必须手动注册实例而不是仅注册其类型。这样,您可以将所需的参数传递给RegisterInstance方法。
在我的情况下,没有必要注册父服务,因为它是抽象的,因此不会被注入任何地方。
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
object parameter = new object();
ServiceLocator.Default.
RegisterInstance<INthChildService>(new NthChildService(parameter));
}
}