Resolve with parameter from other constructor with unity

后端 未结 1 746
一整个雨季
一整个雨季 2021-01-26 07:43

I\'m using Unity and inject all my dependencies. Let\'s say that I have a Manager class like so

public class Manager : IManager
{
    public Manager         


        
相关标签:
1条回答
  • 2021-01-26 08:33

    I register all my types at service startup, but at startup i do not know the "customerName"-parameter

    In other words, your customerName parameter is runtime data. Injecting runtime data into components during the components' initialization is an anti-pattern.

    There are two possible solutions to your problem, but in your your case, the most likely solution is to pass through the parameter through the public API as follows:

    public class Service
    {
        private readonly IManager _manager;
    
        public Service(IManager manager) {
            _manager = manager;
        }
    
        public void ServiceCall(string customerName) {
            _manager.DoSomething(customerName);
        }
    }
    

    Here the IManager interface is changed so that the customerName is passed through the DoSomething method. Because the runtime value isn't needed anymore during construction, there is no need to inject the Unity container into the Service (which is a form of the Service Locator anti-pattern).

    For the second option, please read this article.

    0 讨论(0)
提交回复
热议问题