简体   繁体   中英

How to use Structure map for DI if some constructor parameters need to be passed manually

I am facing a situation where my Class constructor takes 2 parameters. One parameter needs to be passed manually by the calling object while the other parameter should be injectd by Structuremap. I want to expose only one constructor that takes parameter value that should be passed manually. I want to hide the second parameter as it should be handled by Structure map itself. Can anyone suggest how it can be done.

I have a scenario like this

public class ProcessPayments
{
    public ProcessPayments(String accountNumber, IProcessPayments paymentProcesser)
    {
        ...
    }
}

I want to expose the constructor with only first parameter like so

var P = new ProcessPayments("123");

I want Structure Map to automatically inject the IProcessPayments dependency for me based on my configuration.

How can I achieve this?

I can do something like this in my constructor

public ProcessPayments(String accountNumber)
{
    _AccountNumber = accountNumber;
    _ProcessPayments = ObjectFactory.GetInstance<IProcessPayments >();
}

But this would mean that now I have a dependency on Structure Map itself and I don't like this option. Any other elegant solution?

It seems that accountNumber is a runtime dependency/value (it can change from call to call). Do not mix runtime values with compile/registration time dependencies. Instead pass the accountNumber on using a method:

public class ProcessPayments
{
    public ProcessPayments(IProcessPayments paymentProcesser) { ... }

    public void Process(String accountNumber) { ... }
}

Or, if that's not appropriate, create a factory:

public class ProcessPaymentsFactory : IProcessPaymentsFactory
{
    public ProcessPaymentsFactory(IProcessPayments paymentProcesser) { ... }

    public ProcessPayments Create(String accountNumber)
    {
        return new ProcessPayments(accountNumber, this.paymentProcesser);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM