Register a "default" for ResolveNamed()?

May 7, 2009 at 4:35 AM
Just found another thing that would be nice to have.

I have this code to return the appropriate page given a string:

    _container.Register<PigFinderPage>("TAG", c => new PigsPages.TagSearchPage(c.Resolve<PigsProvider>()));
    _container.Register<PigFinderPage>("LOC", c => new PigsPages.PenSearchPage(c.Resolve<PigsProvider>()));

... and I resolve the page like this:

    c.ResolveNamed<PigFinderPage>(Session.Current.User["PFC_ID"])

So depending on what the value of the "PFC_ID" setting is for the current user, I get a different PigFinderPage instance back. This works really well.

However, if for some reason the "PFC_ID" setting is set to an invalid value (one whose name I have not registered) then Funq will throw an exception when I try to resolve it.

Would it be possible to allow me to register a "default" named instance? One that is returned if there's no named registration for the given string? I suppose this could work two ways; either at registration time:

    _container.RegisterDefault<PigFinderPage>("LOC", c => new PigsPages.PenSearchPage(c.Resolve<PigsProvider>()));
    c.ResolveNamed<PigFinderPage>("blah") // returns PenSearchPage

... or at resolution time:

    c.ResolveNamed<PigFinderPage>("blah", "LOC") // returns PenSearchPage (based on the second parameter)

I could probably fudge this if there was a "CanResolve<T>(string name)" method, but I think it would be cleaner code if there was an overload of ResolveNamed that I could use instead.

Matt
Coordinator
May 7, 2009 at 11:51 AM
Or you can do the following with the current bits:

c.TryResolveNamed<PigFinderPage>("blah") != null ? c.ResolveNamed<PigFinderPage>("blah")  : c.ResolveNamed<PigFinderPage>("LOC")

You're resolving twice, which may have a perf. impact.
Not sure if the following compiles:

PigFinderPage p;

p = c.TryResolveNamed<PigFinderPage>("blah") != null ? p : c.ResolveNamed<PigFinderPage>("LOC")



May 7, 2009 at 12:03 PM
Yeah I was thinking about something tricky with the "??" operator, but some way to register a default would clean the code up somewhat. Smile emoticon

From: [email removed]
Sent: Thursday, May 07, 2009 9:51 PM
To: [email removed]
Subject: Re: Register a "default" for ResolveNamed()? [funq:55547]

From: dcazzulino

Or you can do the following with the current bits:

c.TryResolveNamed<PigFinderPage>("blah") != null ? c.ResolveNamed<PigFinderPage>("blah") : c.ResolveNamed<PigFinderPage>("LOC")

You're resolving twice, which may have a perf. impact.
Not sure if the following compiles:

PigFinderPage p;

p = c.TryResolveNamed<PigFinderPage>("blah") != null ? p : c.ResolveNamed<PigFinderPage>("LOC")