2

I have a class MyClass with the following constructor:

public MyClass(IRepository repository, AnotherClass anObject) { ... }

The interface IRepository is registered at application startup with Unity 2 to be mapped to a concrete class:

IUnityContainer container = new UnityContainer();
container.RegisterType<IRepository, MyConcreteRepository>();

Now, the concrete instance of the second parameter of the constructor is always different depending on application context. So I cannot register AnotherClass to be a specific instance at startup nor does it make sense to let Unity create an object of that class with its default constructor which would happen if I call:

container.Resolve<MyClass>()

This resolves to new MyClass(new MyConcreteRepository(), new AnotherClass()).

What I am looking for, if I have some given concrete object anObject of type AnotherClass, is a way to tell Unity to resolve MyClass to

new MyClass(new MyConcreteRepository(), anObject)

without permanently registering the instance anObject in the container.

Is this possible and how?

Thank you for help in advance!

asked Jan 27, 2011 at 17:37

1 Answer 1

3

You could use a ParameterOverride:

var myClass = container.Resolve<MyClass>(new ParameterOverride("anObject", anObject));

In case it's not clear given the names used in the sample, this assigns the object anObject to the parameter named "anObject" in the MyClass constructor.

answered Jan 27, 2011 at 17:44
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this works! Unfortunately, it ignores the overridden parameter silently if I should carelessly change the parameter name from anObject to something other like myObject and Unity creates a new default object. In my special situation I would prefer to get a "ParameterNotFound" exception or something like that. But I guess I have to live with that.
Yeah - I wish unity would throw an exception in this case as well. Another thing to look out for is that if you subclass MyClass and use a parameter override, it will ripple through any base() constructor chains.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.