Can I pass constructor parameters to Unity's Resolve() method?

NotDan picture NotDan · Apr 24, 2009 · Viewed 90.9k times · Source

I am using Microsoft's Unity for dependency injection and I want to do something like this:

IDataContext context = _unityContainer.Resolve<IDataContext>();
var repositoryA = _unityContainer.Resolve<IRepositoryA>(context); //Same instance of context
var repositoryB = _unityContainer.Resolve<IRepositoryB>(context); //Same instance of context

IDataContext context2 = _unityContainer.Resolve<IDataContext>(); //New instance
var repositoryA2 = _unityContainer.Resolve<IRepositoryA>(context2);

RepositoryA and RepositoryB both have a constructor that takes an IDataContext parameter, and I want Unity to initialize the repository with the context that I pass it. Also note that IDataContext is not registered with Unity (I don't want 3 instances of IDataContext).

Answer

Exist picture Exist · Sep 22, 2009

As of today they have added this functionality:

It’s in the latest drop here:

http://unity.codeplex.com/SourceControl/changeset/view/33899

Discussion on it here:

http://unity.codeplex.com/Thread/View.aspx?ThreadId=66434

Example:

container.Resolve<IFoo>(new ParameterOverrides<Foo> { { "name", "bar" }, { "address", 42 } });"