Named registration injection based on property name

Sep 3, 2013 at 9:06 AM

I have a question/suggestion. Is there a possibility to inject an implementation based on the property name. For instance, I have one interface with multiple implementations:

Interface IWebHostingProvisioning has ApacheWebHostingProvisioning and NginxWebHostingProvisioning.

In my code I inject them with the unity annotation Dependency("Apache") but therefore I have to make a reference to unity. Could unity also resolve the right implementation based on the property name? Like:

public IWebHostingProvisioning ApacheWebHostingProvisioning { get; set; }

If not, maybe this is a nice feature in an upcomming release?

Thanks, Ron
Sep 3, 2013 at 11:14 AM
If you name the property ApacheWebHostingProvisioning does it make sense that this property is of the interface Type?

With that naming I would expect it to be of the concrete Type ApacheWebHostingProvisioning. Then you don't need any attribute whatsoever.
Sep 3, 2013 at 11:23 AM
I don't have a reference to the type ApacheWebHostingProvisioning. Only a reference to the interface IWebHostingProvisioning. Unity have to inject the implementation ApacheWebHostingProvisioning to that property. And if I name the property NginxWebHostingProvisioning or IisWebHostingProvisioning than unity have to inject that implementation. I'm wondering if this is possible with Unity.
Sep 3, 2013 at 11:51 AM
Unity does not provide this behavior out-of-the-box. Is there a reason why you would like to go with property injection? For mandatory dependencies constructor injection is the way to go. And for that situation there is a solution. Change your consumer class like this:
public class Foo
  private readonly IWebHostingProvisioning apacheWebHostingProvisioning;
  public Foo(IWebHostingProvisioning apacheWebHostingProvisioning)
    if(apacheWebHostingProvisioning == null) throw new ArgumentNullException("apacheWebHostingProvisioning");
    this.apacheWebHostingProvisioning = apacheWebHostingProvisioning;
  public IWebHostingProvisioning WebHostingProvisioning { get { return this.apacheWebHostingProvisioning; } }
And use the solution described in this blog post. Should do the trick.
Sep 3, 2013 at 1:06 PM
Normally I used constructor injection all the time. But because of the named registration I choose to use property injection. I will read the blog post. Thanks in advance.
Sep 3, 2013 at 1:08 PM
It looks like this post is exactly what I need. Thanks for referring!