choose which constructor to use

Aug 30, 2011 at 5:51 AM

I would like to set the registration of a type to a particular constructor.

Is it possible with autoregistration syntax?


Aug 30, 2011 at 10:14 AM
Edited Aug 30, 2011 at 10:15 AM

You can use Include method overload that takes lambda of type and container and then use Unity standard way ( to pick a particular constructor:

.Include(If.Implements<IFoo>, (t, c) => c.RegisterType<Foo>(new InjectionConstructor(new ResolvedParameter<IBar>())))
Aug 30, 2011 at 3:53 PM
Edited Aug 30, 2011 at 3:54 PM

I did read that great post and tried the following.

I don't have direct reference to the concrete implementation, only the interfaces in the host assembly that contains unity.

Everything works until I need a type that has multiple constructors.

This is what I was trying to use for the empty constructor.

.Include(If.Implements<IAmARepository>, (t, c) => c.RegisterType<IAmARepository>(new InjectionConstructor()))

{An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:System.TypeInitializationException: The type initializer 
for 'Host' threw an exception. ----> System.InvalidOperationException: The type IAmARepository does not 
have a constructor that takes the parameters ().   at Microsoft.Practices.Unity.InjectionConstructor.FindConstructor(Type typeToCreate)   
at Microsoft.Practices.Unity.InjectionConstructor.AddPolicies(Type serviceType, Type implementationType, String name, IPolicyList policies)   
at Microsoft.Practices.Unity.UnityContainer.RegisterType(Type from, Type to, String name, LifetimeManager lifetimeManager, InjectionMember[] injectionMembers)

when i try something like

 .Include(If.Implements<IAmARepository>, (t, c) => c.RegisterType(typeof(IAmARepository), t, nullnew InjectionConstructor()))
It says it not a delegate type and won't compile.  Its an Action.  =(

Any ideas?

Aug 30, 2011 at 5:46 PM

I should add that this registers them but without any service/interface signature

                    .Include(If.Implements<IAmABestAvailableVolumeRepository>, (t, c) => c.RegisterType(t, new InjectionConstructor()))
Aug 30, 2011 at 10:00 PM

This works.  I had a brain lapse.  Thank you for your time!

 .Include(If.Implements<IAmARepository>, (t, c) => c.RegisterType(typeof(IAmARepository), t, new InjectionConstructor()))