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注册 ...
随机推荐
- [NHibernate]增删改操作
目录 写在前面 文档与系列文章 添加数据 删除数据 修改数据 添加修改数据 总结 写在前面 上篇文章介绍了nhibernate的基于面向对象的条件查询.对一个项目来说,增删改查是必不可少的,虽然实现方 ...
- [NHibernate]存储过程的使用(二)
目录 写在前面 文档与系列文章 创建对象 更新对象 总结 写在前面 上篇文章介绍了如何使用MyGeneration代码生成器生成存储过程,以及nhibernate中通过存储过程删除数据的内容,这篇文章 ...
- english
I will keep you posted. :我会随时通知您. wow! :(表示极大的惊奇或钦佩)哇,呀 np :no problem Thanks in advance! :先行感谢 take ...
- 1 web.xml配置详解
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http:// ...
- IK分词器 整合solr4.7 含同义词、切分词、停止词
转载请注明出处! IK分词器如果配置成 <fieldType name="text_ik" class="solr.TextField"> < ...
- 【Go入门教程1】Go 安装,GOROOT,GOPATH,Go工作空间
Go安装 Windows 安装 访问Golang Code下载页,32 位请选择名称中包含 windows-386 的 msi 安装包,64 位请选择名称中包含 windows-amd64 的.下载好 ...
- Codeforces 696 D. Legen...
Description 每个字符串有些价值,问生成长度为 \(l\) 的字符串最多能获得多少价值,总字符数不超过 \(200\), \(l\leqslant 10^{14}\) . Sol AC自动机 ...
- MATLAB的SAVE命令动态批量保存TXT文件
1.使用save(): for i=1:6 str=[num2str(i),’.txt’]; m=[1 2; 3 4]; save(str,’m’,’-ascii’);%注意m的单引号,一定记得加上, ...
- 使用Angular2理由
1. 组件化 组件化编程是web 发展的一个趋势,Angular2提供高效简单的组件开发方式,使程序开发更加关注业务逻辑的实现,而不用关心如何加载组件和模块,如何引用及依赖注入的实现等. 如下代码所示 ...
- macbook air 开机黑屏解决方法
故障现象:1. 开机有声音2. 背面logo亮灯3. 键盘背光灯不亮4. 大写锁定键按下不亮5. 屏幕黑屏,无苹果logo 解决:重置PRAM后成功开机. 1. 关闭 Mac.2. 在键盘上找到以下按 ...