Search code examples
c#.netdependency-injectionunity-containerconstructor-injection

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


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).


Solution

  • 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 } });"