简单的注射器:注册开放式泛型类型与构造函数的参数
我已经创建了一个泛型类型简单的注射器:注册开放式泛型类型与构造函数的参数
public interface IContext<T> {}
而且,我有一个类型实现的是(与参数的构造函数)
public class Context<T> : IContext<T> { public Context(string url, string key) { } ... }
我想注册简单的注射器。通过下面的代码,我不知道如何通过值构造
container.Register(typeof(IContext<>), typeof(Context<>))
This一个显示了一种方法,如果我在构造函数的参数传递的类型。但是,对我而言,它只是原始类型。看起来像是通过压倒一切的施工解决方案行为,我可能做到这一点。但是,真的不知道我该如何利用它。有人能指导我找到一个合适的方式来注册吗?
在将原始依赖关系转换为开放通用注册时,典型的解决方案是将一组配置值提取到DTO中,并将该DTO注入到类型的构造函数中;这可以让你新的配置对象为单登记到container:
我已经创建了一个泛型类型
公共接口IContext {}
而且,我已经实现了一个类型(有一个构造函数与参数)
public class ContextConfiguration
{
public readonly string Url;
public readonly string Key;
public ContextConfiguration(string url, string key) { ... }
}
public class Context<T> : IContext<T>
{
public Context(ContextConfiguration config)
{
}
...
}
// Configuration
container.RegisterSingleton(new ContextConfiguration(...));
container.Register(typeof(IContext<>), typeof(Context<>));
如果你不能改变该类型的构造函数中,创建一个子类,类型您将Composition Root内的。该子类型再次使用该配置DTO:
// Part of the Composition Root
private class ContextConfiguration
{
public readonly string Url;
public readonly string Key;
public ContextConfiguration(string url, string key) { ... }
}
private class CompositionRootContext<T> : Context<T>
{
public Context(ContextConfiguration config) : base(config.Url, config.Key)
{
}
...
}
// Configuration
container.RegisterSingleton(new ContextConfiguration(...));
container.Register(typeof(IContext<>), typeof(CompositionRootContext<>));
如果Context<T>
是密封的,你可以覆盖parameter injection behavior,但在一般情况下,在这种情况下,你是在处理由外部库定义的类型。对于外部类型,通常最好将它们隐藏在应用程序定制的抽象之后(根据DIP)。不要让应用程序代码依赖于IContext<T>
,而是让应用程序依赖于应用程序定义的接口。作为组合根的一部分,您可以实现一个Adapter,将特定于应用程序的界面调整为Context<T>
。该适配器的构造函数将能够使用该配置DTO。
感谢您的见解史蒂文。我想我可以按照你的建议创建一个DTO。但是,为什么我会将其注册为单身人士?我不能在运行时传递参数吗? (我的要求也是在运行时通过它们) –
@AthiS:啊,那是你的问题中缺少的一些重要信息。值是_runtime _data_。请阅读[本文](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=99)。它描述了如何处理运行时数据。 – Steven
有趣的阅读史蒂文。通过输入,我改变了设计,以便运行时数据不会通过构造函数传递 –