Resolving named dependencies with Unity

前端 未结 2 1949
醉酒成梦
醉酒成梦 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:07

    Still have no idea why your version doesn't work but this DOES work (as I've expected):

            var container = new UnityContainer();
            container
                .RegisterType()
                .RegisterType( "FooGateway", new InjectionConstructor( "I am foo" ) )
                .RegisterType( "BarGateway", new InjectionConstructor( "I am bar" ) )
                //.RegisterType( new InjectionConstructor( new ResolvedParameter(), new ResolvedParameter( "FooGateway" ) ) )
                //.RegisterType( new InjectionConstructor( new ResolvedParameter(), new ResolvedParameter( "BarGateway" ) ) );
                .RegisterType( new InjectionFactory( c => new Service( c.Resolve(), c.Resolve( "FooGateway" ) ) ) )
                .RegisterType( new InjectionFactory( c => new Service( c.Resolve(), c.Resolve( "BarGateway" ) ) ) );
    

    Note that I am using InjectionFactory instead of InjectionConstructor.

    Yet another version that works. This time I keep your way of registering services but I make them named and resolve by name:

            var container = new UnityContainer();
            container
                .RegisterType()
                .RegisterType( "FooGateway", new InjectionConstructor( "I am foo" ) )
                .RegisterType( "BarGateway", new InjectionConstructor( "I am bar" ) )
                .RegisterType( "sf", new InjectionConstructor( new ResolvedParameter(), new ResolvedParameter( "FooGateway" ) ) )
                .RegisterType( "sb", new InjectionConstructor( new ResolvedParameter(), new ResolvedParameter( "BarGateway" ) ) );
                //.RegisterType( new InjectionFactory( c => new Service( c.Resolve(), c.Resolve( "FooGateway" ) ) ) )
                //.RegisterType( new InjectionFactory( c => new Service( c.Resolve(), c.Resolve( "BarGateway" ) ) ) );
    
    
            var barGateway = container.Resolve( "BarGateway" );
            var fooGateway = container.Resolve( "FooGateway" );
    
            var serviceBar = container.Resolve( "sb" );
            var serviceBarGatewayName = serviceBar.DoSomething();
    
            var serviceFoo = container.Resolve( "sf" );
            var serviceFooGatewayName = serviceFoo.DoSomething();
    

提交回复
热议问题