Unity构造函数注入其他参数

Eve*_*ttE 11 c# oop unity-container

我有一个类,其构造函数如下所示:

public BatchService(IRepository repository, ILogger logger, string user)
Run Code Online (Sandbox Code Playgroud)

在我的DI bootstrapper类中,我有以下RegisterType命令:

.RegisterType<BatchService>(
    new InjectionConstructor(
        new ResolvedParameter<IRepository>("SomeRepository"), 
        new ResolvedParameter<ILogger>("DatabaseLogger")))
Run Code Online (Sandbox Code Playgroud)

在我的客户端代码中,我想实例化BatchService如下:

BatchService batchService = DIContainer.Resolve<BatchService>()
Run Code Online (Sandbox Code Playgroud)

如您所见,我有一个字符串参数user作为构造函数的一部分被调用BatchService,它不是DI逻辑的一部分.如果我需要userBatchService课堂上使用,我应该如何最好地处理这种情况?

Seb*_*ber 8

请不要滥用Unity作为ServiceLocator.

如果要创建需要运行时参数的对象,请使用工厂.您甚至可以通过使用Unity版本的Typed Factories来放弃实现该工厂的行为,或者让Unity为您生成工厂代理.


sth*_*ura 5

您可以使用ParameterOverride

BatchService batchService = 
DIContainer.Resolve<BatchService>(new ParameterOverride("user", valueForUser));
Run Code Online (Sandbox Code Playgroud)