带有其他参数的Unity构造函数注入 [英] Unity constructor injection with other parameter
问题描述
我有一个带有构造函数的类,如下所示:
I have a class with a constructor that looks like the following:
public BatchService(IRepository repository, ILogger logger, string user)
在我的DI引导程序类中,我具有以下RegisterType
命令:
In my DI bootstrapper class, I have the following RegisterType
command:
.RegisterType<BatchService>(
new InjectionConstructor(
new ResolvedParameter<IRepository>("SomeRepository"),
new ResolvedParameter<ILogger>("DatabaseLogger")))
在我的客户代码中,我要实例化BatchService
,如下所示:
In my client code, I want to instantiate BatchService
as follows:
BatchService batchService = DIContainer.Resolve<BatchService>()
如您所见,我有一个名为user
的字符串参数,它是BatchService
的构造函数的一部分,它不是DI逻辑的一部分.如果需要在BatchService
类中使用user
,如何最好地处理这种情况?
As you can see, I have a string parameter called user
as part of the constructor to BatchService
that is not part of the DI logic. How should I best handle this situation if I need to use user
in the BatchService
class?
推荐答案
请不要如果要创建需要运行时参数的对象,请使用工厂.您甚至可以通过使用类型化工厂或让Unity为您生成工厂代表.
If you want to create objects that need runtime parameters use a factory. You can even drop the act of implementing that factory by either using the Unity version of Typed Factories or let Unity generate factory delegates for you.
这篇关于带有其他参数的Unity构造函数注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!