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注册 ...
随机推荐
- QT中使用函数指针
想仿命令行,所以定义了一个类,让一个String 对应一个 function,将两者输入list容器. 类中定义了 QString commandStr; void (MainWindow::*com ...
- javascript数据结构与算法---队列
javascript数据结构与算法---队列 队列是一种列表,不同的是队列只能在队尾插入元素,在队首删除元素.队列用于存储按顺序排列的数据,先进先出,这点和栈不一样(后入先出).在栈中,最后入栈的元素 ...
- AOP基本名词解释
- App- 借书趣
借书趣是一款方便用户在上海图书馆借书助手应用.通过扫描条码,导入豆瓣想读等手段可以方便管理想读想借的书目应用通过上图的接口和一些算法帮助用户生成借书单,规划用户可以去上图的哪个分馆可以借到最多想要阅读 ...
- 如何用angularjs给从后台传来数据添加链接
<!DOCTYPE html> <html ng-app="myApp"> <head> <meta charset="UTF- ...
- 编译Android源码
编译版本要求 基本安装环境 ubuntu 14.04 64 sudo apt-get install git-core gnupg flex bison gperf build-essential \ ...
- .NET LINQ基本查询操作
获取数据源 在 LINQ 查询中,第一步是指定数据源.像在大多数编程语言中一样,在 C# 中,必须先声明变量,才能使用它.在 LINQ 查询中,最先使用 from 子句的目的是引入数据源 ( ...
- java面试题及答案(转载)
JAVA相关基础知识1.面向对象的特征有哪些方面 1.抽象:抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面.抽象并不打算了解全部问题,而只是选择其中的一部分,暂时 ...
- resultMap 映射
1. sql的重用:定义一个sql片段,可在任何SQL语句中重用该片段. <sql id="personColumns"> name, sex, updateTime& ...
- LeetCode之371. Sum of Two Integers
---------------------------------- 使用位运算实现加法: a^b 加不同部分(a&b)<<1 加相同部分递归相加 AC代码: public cla ...