配置运行时支持数组

  



class Foot{ 

public Foot(IBar[] bars) 

{ }

 }


 

 



container.Configure<InjectedMembers>()


 .ConfigureInjectionFor<Foot>(


 new InjectionConstructor(new ResolvedArrayParameter<IBar>());


 

 

 

 


微软企业库4.1学习笔记(二十六)Unity依赖注入模块3_微软企业库4.1微软企业库4.1学习笔记(二十六)Unity依赖注入模块3_微软企业库4.1_02代码


container.Configure<InjectedMembers>() 


    .ConfigureInjectionFor<Foot>( 


        new InjectionConstructor(


        new ResolvedArrayParameter<IBar>( typeof(IBar), new ResolvedParameter<IBar>("some named bar"), new BarImpl()))


 

   运行的时候配置容器

  1、配置构造函数,属性,和方法注入

  你可以在运行的时候,直接创建和加载配之类来配置Unity容器实现注入功能。除去在属性添加attribute和使用配置文件之外,又提供了一种方法。

  使用InjectionConstructor,InjectionProperty和InjectionMethod类联合Configure和ConfigureInjectionFor方法为容器指定依赖注入的参数。

  

 



IUnityContainer container = new UnityContainer() 


.RegisterType<AType>(new InjectionConstructor()); 


 


AType aType = container.Resolve<AType>(); 


Assert.IsTrue(aType.DefaultConstructorCalled);


 

   下面的代码示例了如何使用Configuration类配置构造函数注入、属性注入、和方法注入。

 


微软企业库4.1学习笔记(二十六)Unity依赖注入模块3_微软企业库4.1微软企业库4.1学习笔记(二十六)Unity依赖注入模块3_微软企业库4.1_02代码


IUnityContainer myContainer = new UnityContainer();


 myContainer.Configure<InjectedMembers>() 


.ConfigureInjectionFor<MyObject>(


   new InjectionConstructor(12, "Hello Unity!"), 


  new InjectionProperty("MyProperty"), 


  new InjectionProperty("MyStringProperty", "SomeText"), 


  new InjectionMethod("InitializeMe", 42.0, 


  new ResolvedParameter(typeof(ILogger), "SpecialLogger")


  ) 


);


 

  这种API动态配置注入提供了足够的灵活性,保留了简易、直观的使用方式。

  这种配置注入的API是以InjectionParameterValue的子类为基础。当然在建立注入的时候也可以提供其他类型的对象。根据下面的规则,提供的对象将会被翻译成InjectionParameterValue类型。

  1)如果对象是InjectionParameterValue的子类实例的话,注入系统将会使用这个对象。

  2)如果对象是Type的实例,注入系统会创建一个ResolvedParameter作为注入之后返回的类型。

  3)如果是其他对象,配置API会创建一个InjectionParameterValue实例,容器会产生一个属性注入。

  

未完待续。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。