Optional Dependency Resolution, If Mapping Exists

Aug 20, 2008 at 8:49 PM
Hi there.

I have an abstract Base Class that has a few public properties, which are resolved through Unity using Property Injection and Interface Mapping.  These interfaces are Generic though, and so I'd like a way to optionally resolve them if there is a concrete mapping found in config, otherwise not.

For example, imagine the following property:

IQueryOptimizer<TEntity> Service {get;set;}

TEntity is a generic constraint passed up to this class by the inheritor.

In config, I map each Interface TEntity seperately:

<type type="IQueryOptimizer`1[[Models.Entity, Models]], Models" mapTo="Models.EntityQueryOptimizer, Models" />
<type type="IQueryOptimizer`1[[Models.AnotherEntity, Models]], Models" mapTo="Models.AnotherEntityQueryOptimizer, Models" />

This way, I can create specific implementations for things like optimization or validation, but have them injected automatically into the framework using one common Generic Interface.

That works great, except, resolution fails if the mapping isn't found in config.  So, if another developer creates a third class, called "MyThirdEntity" Unity will throw a ResolutionFailedException because the developer also has to create and Map the following service.
<type type="IQueryOptimizer`1[[Models.MyThirdEntity, Models]], Models" mapTo="Models.MyThirdEntityQueryOptimizer, Models" />

What ends up happening, is developers create a bunch of empty classes to satisfy Unity, many of which are never used.

I'd obviously like these hooks to be OPTIONAL.  So that if a developer chooses to create and map a custom Optimization or Validation class for a service, it will be resolved for them and the Base class will take advantage of it.  But in the event that they haven't created anything, it just continues on as normal.  This is a much more flexible development scenario.

However, I'm not sure how to best achieve this.

I can pull out all the [Dependency] attributes from the properties, and then resolve manually in the base class, attempting to catch all the ResolutionFailedExceptions, but that seems like a hack.

Is there a way to tell Unity to simply return NULL if the mapping is not found in config, rather than throw an exception?


Aug 21, 2008 at 12:07 AM
What I've ended up doing that's working fine, is just having a Generic Resolution in config for each Service, and that gets mapped first.  Subsequently, Developers can define more explicit resolutions for some of the types and the container will pick that up and inject those in that case.

Best of both worlds, and requires no C#, so I like it :).
Aug 21, 2008 at 5:57 PM
Take a look at the Extensibility Webcast Demos available here. The webcast recording itself has apparently been lost, but the demo includes code for an OptionalDependency that does exactly what you're asking for.