带有其他参数的Unity构造函数注入 [英] Unity constructor injection with other parameter

查看:126
本文介绍了带有其他参数的Unity构造函数注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆