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!
1 Answer 1
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.
2 Comments
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.Explore related questions
See similar questions with these tags.