Unity constructor injection with other parameter

亡梦爱人 提交于 2019-11-30 02:37:21

问题


I have a class with a constructor that looks like the following:

public BatchService(IRepository repository, ILogger logger, string user)

In my DI bootstrapper class, I have the following RegisterType command:

.RegisterType<BatchService>(
    new InjectionConstructor(
        new ResolvedParameter<IRepository>("SomeRepository"), 
        new ResolvedParameter<ILogger>("DatabaseLogger")))

In my client code, I want to instantiate BatchService as follows:

BatchService batchService = DIContainer.Resolve<BatchService>()

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?


回答1:


Please don't abuse Unity as a ServiceLocator.

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.




回答2:


You can use ParameterOverride:

BatchService batchService = 
DIContainer.Resolve<BatchService>(new ParameterOverride("user", valueForUser));



回答3:


First of all it's not good idea mix ILogger with business logic. You can create ILogger directly in BatchService or resolve thru [Dependency] attribute. DI it's not panacea, business object creation shouldn't depend from ILogger

Use new InjectionParameter<string>("user") Take a look please Registering Injected Parameter and Property Values for more details



来源:https://stackoverflow.com/questions/11994952/unity-constructor-injection-with-other-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!