[英]Unity constructor injection with other parameter
我有一个类,其构造函数如下所示:
public BatchService(IRepository repository, ILogger logger, string user)
在我的DI bootstrapper类中,我有以下RegisterType
命令:
.RegisterType<BatchService>(
new InjectionConstructor(
new ResolvedParameter<IRepository>("SomeRepository"),
new ResolvedParameter<ILogger>("DatabaseLogger")))
在我的客户端代码中,我想实例化BatchService
,如下所示:
BatchService batchService = DIContainer.Resolve<BatchService>()
如您所见,我有一个名为user
的字符串参数作为BatchService
的构造函数的BatchService
,它不是DI逻辑的一部分。 如果我需要在BatchService
类中使用user
,我应该如何最好地处理这种情况?
如果要创建需要运行时参数的对象,请使用工厂。 您甚至可以通过使用Unity版本的Typed Factories来放弃实现该工厂的行为,或者让Unity为您生成工厂代理 。
您可以使用ParameterOverride
:
BatchService batchService =
DIContainer.Resolve<BatchService>(new ParameterOverride("user", valueForUser));
首先,将ILogger
与业务逻辑混合起来并不是一个好主意。 您可以直接在BatchService
创建ILogger或通过[Dependency]
属性解析。 DI它不是灵丹妙药,业务对象的创建不应该依赖于ILogger
使用new InjectionParameter<string>("user")
请查看注册注入的参数和属性值以获取更多详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.