如何使用构造函数参数注册继承服务?
问题描述:
我有一个父级抽象服务,有自己的接口。如何使用构造函数参数注册继承服务?
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>();
答
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));
}
}
而作为一个额外的评论,你可以这样做既自定义参数,并自动完成其他服务相结合: _typeFactory.CreateInstanceWithParametersAndAutoCompletion(参数); –
2015-02-06 11:01:23
有趣的是,在这种情况下,自动补全意味着什么? – Kilazur 2015-02-06 11:05:41
如果您添加服务定位器中的其他参数,它们将自动追加。所以你可以有NthChildService(FirstObject obj,IRegisteredType1 type1,IRegisteredType2 type2等) – 2015-02-06 12:32:17