配置运行时支持数组
class Foot{
public Foot(IBar[] bars)
{ }
}
container.Configure<InjectedMembers>()
.ConfigureInjectionFor<Foot>(
new InjectionConstructor(new ResolvedArrayParameter<IBar>());

代码
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类配置构造函数注入、属性注入、和方法注入。

代码
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实例,容器会产生一个属性注入。
未完待续。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构