Resolving named dependencies with Unity

前端 未结 2 1947
醉酒成梦
醉酒成梦 2021-01-12 08:49

I have a service with 2 dependencies: a Repository and a Gateway (sms).

I need to resolve 2 different versions of the service that only differ on one of the paramete

2条回答
  •  礼貌的吻别
    2021-01-12 09:12

    it can also be done using ParameterOverride as below

            container
                .RegisterType()
                .RegisterType("FooGateway", new InjectionConstructor("I am foo"))
                .RegisterType("BarGateway", new InjectionConstructor("I am bar"))
                .RegisterType(new InjectionConstructor(new ResolvedParameter(), typeof(IGateway)))
                .RegisterType(new InjectionConstructor(new ResolvedParameter(), typeof(IGateway)));
    
            var barGateway = container.Resolve("BarGateway");
            var fooGateway = container.Resolve("FooGateway");
    
            var serviceBar = container.Resolve(new ParameterOverride("gateway", barGateway));
            var serviceBarGatewayName = serviceBar.DoSomething();
    
            var serviceFoo = container.Resolve(new ParameterOverride("gateway", fooGateway));
            var serviceFooGatewayName = serviceFoo.DoSomething();
    
            Assert.AreEqual("I am bar", barGateway.Name); // pass
            Assert.AreEqual("I am foo", fooGateway.Name); // pass
    
    
            Assert.AreEqual("I am bar", serviceBarGatewayName); // pass
            Assert.AreEqual("I am foo", serviceFooGatewayName); // pass
    

提交回复
热议问题