Unity - Inject different classes for the same interface

后端 未结 3 917
野性不改
野性不改 2021-02-04 07:03

I have one interface: IFoo
Two classes implementing that interface: FooOne and FooTwo
And two classes ClassOne and

3条回答
  •  醉酒成梦
    2021-02-04 07:48

    Have a look at the Unity documentation.

    For a more readable config file you should define type aliases for IFoo, FooOne, FooTwo, ClassOne and ClassTwo. Then you need to register the mappings from IFoo to your implementations. You need to set a name for the mappings. For the consumers of IFoo you need to register an InjectionConstructor.

    Your config will look something like this:

    
    
      
        

    That's the corresponding test that shows how it works.

    UnityConfigurationSection config =
      (UnityConfigurationSection) ConfigurationManager.GetSection("unity");
    IUnityContainer container = new UnityContainer();
    container.LoadConfiguration(config);
    ClassTwo two = container.Resolve();
    Assert.IsInstanceOfType(two.Foo, typeof(FooTwo));
    

    Update

    At runtime you can do it like this

    IUnityContainer container = new UnityContainer();
    container.RegisterType("One");
    container.RegisterType("Two");
    container.RegisterType(new InjectionConstructor(
      new ResolvedParameter("One")));
    container.RegisterType(new InjectionConstructor(
      new ResolvedParameter("Two")));
    

提交回复
热议问题