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注册 ...
随机推荐
- [Maven] 变态问题收集
1.新换的系统,eclipse运行起来之后,一直报错Missing artifact 折腾了好久,没法了,把服务器上的仓库直接压缩,传到本地计算机上,覆盖本地仓库,完美解决这个问题! 2.tomcat ...
- java 实现文件下载
需求:把每天产生的日志文件,从服务器上下载下来 File file = new File(path); // 根据路径,获取File String filename = file.getName(); ...
- 在ie浏览器,360浏览器下,margin:0 auto;不居中的原因
转自 http://blog.sina.com.cn/s/blog_6eef6bf60100nn4m.html margin:0 auto:不居中可能有以下两个的原因 没有设置宽度 看看上面的代码,根 ...
- 微信公众平台推出"微信保护"提升微信账号安全 附微信保护开启教程
前两天小美女的微信公众平台要群发消息时提示需要绑定手机才能操作,当时还以为是动态ip的问题,今天微信公众平台安全中心就说升级了,原来那时已经在公测了.微信公众平台推出"微信保护", ...
- Linux线程同步:条件变量
条件变量通过允许线程阻塞和等待另一个线程发送信号的方法弥补了互斥锁的不足,它常和互斥锁一起使用.使用时,条件变量被用来阻塞一个线程,当条件不满足时,线程往往解开相应的互斥锁并等待条件发生变化.一旦其它 ...
- 在浏览器上直接输入url 时,中文传参乱码问题
这样的地址 xxx.asp?name=中国 ,通过 超链接打开这个链接 ,xxx.asp能够成才接收参数,但是如果将地址直接放到浏览器地址栏上,回车, xxx.asp就无法正确接收中文参数,一直显示 ...
- JS表单验证-12个常用的JS表单验证
JS表单验证-12个常用的JS表单验证 最近有个项目用到了表单验证,小编在项目完结后的这段时间把常用的JS表单验证demo整理了一下,和大家一起分享~~~ 1. 长度限制 <p>1. 长度 ...
- JDK source 之 LinkedHashMap原理浅谈
注:本文参考JDK1.7.0_45源码. LinkedHashMap是基于HashMap实现的数据结构,与HashMap主要的不同为每个Entry是使用双向链表实现的,并且提供了根据访问顺序进行排序的 ...
- Ural 1057 Amount of Degrees
Description 问[L,R]中有多少能表示k个b次幂之和. Sol 数位DP. 当2进制时. 建出一个二叉树, \(f[i][j]\) 表示长度为 \(i\) 有 \(j\) 个1的个数. 递 ...
- 编译Android源码
编译版本要求 基本安装环境 ubuntu 14.04 64 sudo apt-get install git-core gnupg flex bison gperf build-essential \ ...