I started doing more and more work with Unity. I notice that Resolver method takes a params argument ResolverOverride.
Can someone give me an example how I can use ResolverOverride or point me some other source where I can get more clues.
As you have noticed this is a new (and really cool feature) of the Unity 2. This feature let you
There is ParameterOverride : ResolverOverride
A ResolverOverride class that lets you override a named parameter passed to a constructor.
DependencyOverride : ResolverOverride
A class that overrides the value injected whenever there is a dependency of the given type, regardless of where it appears in the object graph.
PropertyOverride : ResolverOverride
A ResolverOverride that lets you override the value for a specified property.
Example
using System; using Microsoft.Practices.Unity; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var container = new UnityContainer(); //ParameterOverride example container.RegisterType<IConcreteService, ConcreteService>( new InjectionConstructor(7) //Old way to pass value to constructor - not flexible. //All resolved (without override which appears only in unity 2.0) classes will have val=7 ); var service0 = container.Resolve<IConcreteService>(); Console.WriteLine(service0.Val); //prints 7 var service = container.Resolve<IConcreteService>(new ParameterOverride("val", 3)); Console.WriteLine(service.Val); // prints 3 var service2 = container.Resolve<IConcreteService>(new ParameterOverride("val", 5)); Console.WriteLine(service2.Val); // prints 5 Console.ReadLine(); //DependencyOverride example var b0 = container.Resolve<B>(new DependencyOverride<IConcreteService>(new ConcreteService(42))); Console.WriteLine(b0.Service.Val); //print 42 Console.WriteLine(b0.Service1.Val); //print 42 var b = container.Resolve<B>(new DependencyOverride<IConcreteService>(new ConcreteService(-42))); Console.WriteLine(b.Service.Val); // print -42 Console.WriteLine(b.Service1.Val); // print -42 Console.ReadLine(); //PropertyOverride example var b1 = container.Resolve<B>(new PropertyOverride("Service", new ConcreteService(42)), new PropertyOverride("Service1", new ConcreteService(-42))); Console.WriteLine(b1.Service.Val); //print 42 Console.WriteLine(b1.Service1.Val); //print -42 Console.ReadLine(); } } public interface IConcreteService { int Val { get; set; } } public class ConcreteService : IConcreteService { public int Val { get; set; } public ConcreteService(int val) { Val = val; } } public class B { [Dependency] public IConcreteService Service{ get; set; } [Dependency] public IConcreteService Service1 { get; set; } } }
Have no idea why does Google keeps silent about that.
Quotes are from Unity source code xml docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With