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注册 ...
随机推荐
- 问题解决:psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
错误提示: psql: could not connect to server: No such file or directory Is the server running locally and ...
- CF memsql Start[c]UP 2.0 A
CF memsql Start[c]UP 2.0 A A. Golden System time limit per test 1 second memory limit per test 256 m ...
- 教你摸清 Linux PC 的性能底细?
导读 基准测试是一项测试或一系列测试,用来确定某个计算机硬件运行起来的状况有多好.在许多情况下,“基准测试”实际上等同于“压力测试”.通过测试硬件的极限,然后可以将测得的结果与其他硬件测得的结果作一番 ...
- Apache curator-client详解
Apache curator框架中curator-client组件可以作为zookeeper client来使用,它提供了zk实例创建/重连机制等,简单便捷.不过直接使用curator-client并 ...
- Apache shiro 文章推荐
均为系列文章,篇幅略长,适合入门. shiro源码分析 跟我学shiro
- realloc的使用误区
C语言 realloc() 函数位于 stdlib.h 头文件中,原型为: void *realloc(void *ptr, size_t size); realloc() 会将 ptr 所指向的内存 ...
- iOS开发UI篇—核心动画(基础动画)
转自:http://www.cnblogs.com/wendingding/p/3801157.html 文顶顶 最怕你一生碌碌无为 还安慰自己平凡可贵 iOS开发UI篇—核心动画(基础动画) iOS ...
- October 17th 2016 Week 43rd Monday
You only live once, but if you do it right, once is enough. 人生只有一次,但如果活对了,一次也就够了. Whether you do it ...
- ios如何一个证书多台设备测试
在苹果开发者网站申请的证书,是授权mac设备的开发或者发布的证书,这意味着一个设备对应一个证书,但是99美元账号只允许生成3个发布证书,两个开发证书,这满足不了多mac设备的使用,使用p12文件可以解 ...
- Sublime Text 2报“Decode error - output not utf-8”错误的解决办法
[Decode error - output not utf-8] [Decode error - output not utf-8] 应该怎么办? 这是因为python配置的编译环境的编码不 ...