Unity: Passing Constructor Parameters to Resolve
In this tutorial we will go through of couple different ways of using custom constructor parameters when resolving an instance with Unity:
- By using the built-in ParameterOverride
- By creating a custom ResolverOverride.
Background
When you’re using a DI-container like Unity, you normally don’t have to worry about how the container resolves the new instance. You have configured the container and the container will act based on your configuration. But there may be cases where you have pass in custom constructor parameters for the resolve operation. Some may argue that this screams of bad architecture but there’s situations like bringing a DI-container to a legacy system which may require these kind of actions.
Resolved class
In this tutorial we are resolving the following test class:
public class MyClass{ public string Hello { get; set; } public int Number { get; set; } public MyClass(string hello, int number) { Hello = hello; Number = number; }} |
It is registered to the container using RegisterType-method and without passing in any parameters:
|
1
2
|
var unity = new UnityContainer();unity.RegisterType<MyClass>(); |
So let’s see how we can pass in the “hello” and “number” variables for the MyClass’ constructor when calling Unity’s Resolve.
Unity ResolverOverride
Unity allows us to pass in a “ResolverOverride” when the container’s Resolve-method is called. ResolverOverride is an abstract base class and Unity comes with few of these built-in. One of them is ParameterOverride which “lets you override a named parameter passed to a constructor.”
So knowing that we need to pass in a string named “hello” and an integer called “number”, we can resolve the instance with the help of ParameterOverride:
[Test]public void Test(){ var unity = new UnityContainer(); unity.RegisterType<MyClass>(); var myObj = unity.Resolve<MyClass>(new ResolverOverride[] { new ParameterOverride("hello", "hi there"), new ParameterOverride("number", 21) }); Assert.That(myObj.Hello, Is.EqualTo("hi there")); Assert.That(myObj.Number, Is.EqualTo(21));} |
We pass in two instances of ParameterOverride. Both of these take in the name and the value of the parameter.
Custom ResolverOverride: OrderedParametersOverride
But what if you don’t like passing in the parameter names and instead you want to pass in just the parameter values, in correct order? In order to achieve this we can create a custom ResolverOverride. Here’s one way to do it:
public class OrderedParametersOverride : ResolverOverride{ private readonly Queue<InjectionParameterValue> parameterValues; public OrderedParametersOverride(IEnumerable<object> parameterValues) { this.parameterValues = new Queue<InjectionParameterValue>(); foreach (var parameterValue in parameterValues) { this.parameterValues.Enqueue(InjectionParameterValue.ToParameter(parameterValue)); } } public override IDependencyResolverPolicy GetResolver(IBuilderContext context, Type dependencyType) { if (parameterValues.Count < 1) return null; var value = this.parameterValues.Dequeue(); return value.GetResolverPolicy(dependencyType); }} |
The parameter values are passed in through the constructor and put into a queue. When the container is resolving an instance, the parameters are used in the order which they were given to the OrderedParametersOverride.
Here’s a sample usage of the new OrderedParametersOverride:
[Test]public void TestOrderedParametersOverride(){ var unity = new UnityContainer(); unity.RegisterType<MyClass>(); var myObj = unity.Resolve<MyClass>(new OrderedParametersOverride(new object[] {"greetings", 24 })); Assert.That(myObj.Hello, Is.EqualTo("greetings")); Assert.That(myObj.Number, Is.EqualTo(24));} |
Unity: Passing Constructor Parameters to Resolve的更多相关文章
- Parameter Passing / Request Parameters in JSF 2.0 (转)
This Blog is a compilation of various methods of passing Request Parameters in JSF (2.0 +) (1) f:vi ...
- Effective Java Item2:Consider a builder when faced with many constructor parameters
Item2:Consider a builder when faced with many constructor parameters 当构造方法有多个参数时,可以考虑使用builder方式进行处理 ...
- Effective Java 02 Consider a builder when faced with many constructor parameters
Advantage It simulates named optional parameters which is easily used to client API. Detect the inva ...
- JNI: Passing multiple parameters in the function signature for GetMethodID
http://stackoverflow.com/questions/7940484/jni-passing-multiple-parameters-in-the-function-signature ...
- 链式编程:遇到多个构造器参数(Constructor Parameters)时要考虑用构建器(Builder)
public class NutritionFacts { private final int servingSize; private final int servings; private fin ...
- C# - Passing Reference-Type Parameters
A variable of a reference type does not contain its data directly; it contains a reference to its da ...
- Unity文档阅读 第三章 依赖注入与Unity
Introduction 简介In previous chapters, you saw some of the reasons to use dependency injection and lea ...
- Registering Components-->Autofac registration(include constructor injection)
https://autofaccn.readthedocs.io/en/latest/register/registration.html Registration Concepts (有4种方式来 ...
- Unity依赖注入使用详解
写在前面 构造器注入 Dependency属性注入 InjectionMethod方法注入 非泛型注入 标识键 ContainerControlledLifetimeManager单例 Unity注册 ...
随机推荐
- mahout 安装测试
1 下载 在http://archive.apache.org/dist/mahout下载相应版本的mahout 版本,获取官网查看http://mahout.apache.org 相关的信息
- java运行过程
一.安装环境 大家在开发Java的时候,首先回装一个java的开发环境,一个JDK(也包含了JRE),然后设置环境变量,这个过程我就不细说了,大家装完后有没有发现,在装完这个环境的同时在安装JRE,在 ...
- 每秒执行一个shell脚本(转载)
上周迁移了一台服务器,发现其中一个项目的数据没有更新,查询原服务器的数据,数据有更新,并找到了rsync服务,从其他服务器传输数据,那么如何找到这台服务器?因为是从远程传输到本地,而且不是很频繁, ...
- JavaScript事件处理程序
JavaScript中的事件处理程序主要分为3种: HTML事件处理程序: <script type="text/javascript"> // HTML事件处理程序 ...
- jquery1.9以上版本如何使用toggle函数
toggle() 方法用于绑定两个或多个事件处理器函数,以响应被选元素的轮流的 click 事件. 但是在1.9及以上的版本中已经删除了该功能. 感觉这个功能还是不错的,以下来自网上搜集,可以在js中 ...
- Linux/CentOS优化配置 汇总
[强烈要求做的]CentOS启用sudo,禁用root远程登录 Linux命令行修改IP.网关.DNS.主机名 的方法 Linux开机直接进入“命令行”模式 更改CentOS 6.x yum源为国内1 ...
- Java中普通代码块,构造代码块,静态代码块执行顺序
//执行顺序:(优先级从高到低.)静态代码块>mian方法>构造代码块>构造方法. 其中静态代码块只执行一次.构造代码块在每次创建对象是都会执行. 1 普通代码块 1 //普通代码块 ...
- 06OC之内存管理
在高级语言中,例如C#是通过垃圾回收机制(GC)来解决这个问题,但是在OC并没有类似的垃圾回收机制,因此必须由程序员手动去维护.今天就讲讲OC中的内存管理: 一.内存管理原理 在Xcode4.2之后的 ...
- POJ2195 最小费用流
题目:http://poj.org/problem?id=2195 处理出每个人到每个门的曼哈顿距离,分别建立容量为1费用为曼哈顿距离的边,在源点和每个人人之间建立容量为1费用为0的边,在门和汇点之间 ...
- http协议相关-待续
// 关于http的东西 function httpAction() { // http://localhost/blog/testurl.php?id=5 到目前为止 // 获取当前域名 // 获取 ...