views:

53

answers:

1

Say I have this class

public class MyObject : IObject
{
    public MyObject(IObject2 object2)
    {

    }
}

which I resolve like:

Container.Resolve<IObject>("SomeName");

Is it possible to configure Unity so that whenever an IObject is resolved using any name, then the IObject2 will also be resolved with that same name (assuming it was registered with such a name)?

I'm looking for a way that doesn't use InjectionConstructor, as I son't want to update it for every new name I introduce.

+1  A: 

This ought to work:

container.RegisterType<IObject2, MyObject2>("someName");
// ...
container.RegisterType<IObject, MyObject>("someName",
    new InjectionConstructor(
        new ResolvedParameter<IObject2>("someName")));

If you want to register more names, you could always consider packaging this little snippet into a reusable method that takes the name as an input parameter.

I don't have Unity nearby right now, so this is more or less from memory...

Mark Seemann
I'm looking for a way to do it without specifying an InjectionConstructor.
Meidan Alon
I'm not aware that you can easily do such a thing with Unity, but the question is also whether you want to. Perhaps you could share some details about your scenario and we'll see if we can help you. The correct solution may be something else entirely (I suspect it is).
Mark Seemann
I create several types of IObject during a single request on my app, say MyObject and OtherObject. Each type has an underlying hierarchy of objects to match.I want that when a type is created based on name x, its hierarchy will also be created based on name x, so if a MyObject is created its IObject2 will be of type MyObject2, and if a OtherObject is created, its IObject2 will be of type OtherObject2.
Meidan Alon
I still don't feel that I have a good view of *why* you want to do that, but it sounds to me like what you really need is an Abstract Factory. Perhaps this will shed a little light on what I mean: http://stackoverflow.com/questions/1686760/which-di-container-will-satisfy-this/1686887#1686887
Mark Seemann
thanks, but my constructors have only dependency parameters, I just want to propagate down the name used for resolving each parameter.I'll try to rephrase my question later.
Meidan Alon
That's probably a good idea. It sounds like you have parallel hierarchies, and you may be better off explicitly modeling this than by relying on a (hypothetical) feature of a particular DI Container.
Mark Seemann