9

I have a class with two ctors. One parameterless and one with parameters.
Unity will by default take the gready approach and go for the last ctor.

How can I define what ctor to use (I want to parameterless) without adding dependency on Unity within my classes? I think it is possible to do it in my container creation, but I don't know how.

Currently my registration entry looks like this:

container.RegisterType<IConfigurationService, SqlConfigurationService>()

UPDATE
I'm trying to avoid programming in XML (config file) as much as possible.

EXTRA
How would registering a constructor with one parameter (which in it's turn should be injected)?
Say ILoggerService is already registered and I would want to use the constructor

public SqlConfigurationService(ILoggerService logger){}

3 Answers 3

19

I don't have Unity nearby right now, but as far as I recall, you can do something like this:

container.RegisterType<IConfigurationService, SqlConfigurationService>(
    new InjectionConstructor())
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks :) Do you per chance also know how to solve my extra question (bottom of OP)?
Total guess after looking a bit at the API docs: container.RegisterType<IConfigurationService, SqlConfigurationService>(new InjectionConstructor(new ResolvedParameter<ILoggerService>()));
0

I think you can also pass in an InjectionConstructor (including ResolvedParameter<T>s for the parameters) in your registration. Have you tried that?

Comments

0

You can apply the InjectionConstructor attribute to the constructor you want to use. This does have the disadvantange of moving some container configuration away from a central location however.

1 Comment

I don't want to add any dependency in my actual classes (ref OP)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.