In this tutorial we will go through of couple different ways of using custom constructor parameters when resolving an instance with Unity:

  1. By using the built-in ParameterOverride
  2. 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的更多相关文章

  1. 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 ...

  2. Effective Java Item2:Consider a builder when faced with many constructor parameters

    Item2:Consider a builder when faced with many constructor parameters 当构造方法有多个参数时,可以考虑使用builder方式进行处理 ...

  3. 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 ...

  4. JNI: Passing multiple parameters in the function signature for GetMethodID

    http://stackoverflow.com/questions/7940484/jni-passing-multiple-parameters-in-the-function-signature ...

  5. 链式编程:遇到多个构造器参数(Constructor Parameters)时要考虑用构建器(Builder)

    public class NutritionFacts { private final int servingSize; private final int servings; private fin ...

  6. C# - Passing Reference-Type Parameters

    A variable of a reference type does not contain its data directly; it contains a reference to its da ...

  7. Unity文档阅读 第三章 依赖注入与Unity

    Introduction 简介In previous chapters, you saw some of the reasons to use dependency injection and lea ...

  8. Registering Components-->Autofac registration(include constructor injection)

    https://autofaccn.readthedocs.io/en/latest/register/registration.html Registration Concepts  (有4种方式来 ...

  9. Unity依赖注入使用详解

    写在前面 构造器注入 Dependency属性注入 InjectionMethod方法注入 非泛型注入 标识键 ContainerControlledLifetimeManager单例 Unity注册 ...

随机推荐

  1. SQL Server 2012复制教程以及复制的几种模式

    简介 SQL Server中的复制(Replication)是SQL Server高可用性的核心功能之一,在我看来,复制指的并不仅仅是一项技术,而是一些列技术的集合,包括从存储转发数据到同步数据到维护 ...

  2. Spring 入门知识

    ------------------------------------------------------------------------------------- Spring是什么? Spr ...

  3. JSP入门

    JSP简介 所谓JSP就是在网页文件中嵌入Java代码或JSP定义的一些标记.JSP是建立在Servlet上的,在执行时JSP容器会先将JSP文件转换成Servlet文件以及class 文件,然后再执 ...

  4. DbHelper为什么要用Using?

    我们分析一下DbHelper做什么事情,大家都知道它用于数据库的连接操作,这里的数据库连接会创建非托管资源,c#的垃圾回收机制不会对它处理,需要实现IDisposable接口手动释放.   手动释放的 ...

  5. Ubuntu14.04 lamp环境 php 无法加载mcrypt扩展

    Ubuntu14.04中安装后的LAMP环境(http://www.cnblogs.com/daiyu/p/4380657.html)中没有加载:mcrypt扩展,后期再laravel5使用中发现报错 ...

  6. css3的基本样式

    一.css3字体(@font-face) 二.css3动画 三.css3多列 四.CSS3 outline-offset 属性 五.CSS3 resize 属性

  7. Github.com上有哪些比较有趣的PHP项目?

    链接就不贴了,可以在github上进行搜索.这里就不列举 symfony.laravel 这些大家都知道的项目了.只列举比较有意思的. swoole, C扩展实现的PHP异步并行网络通信框架,可以重新 ...

  8. jQuery源码笔记(二):定义了一些变量和函数 jQuery = function(){}

    笔记(二)也分为三部分: 一. 介绍: 注释说明:v2.0.3版本.Sizzle选择器.MIT软件许可注释中的#的信息索引.查询地址(英文版)匿名函数自执行:window参数及undefined参数意 ...

  9. word20161206

    D-channel / D 信道 DACL, discretionary access control list / 自由访问控制列表 daily backup / 每日备份 Data Communi ...

  10. git 教程(15)--分支管理策略

    通常,合并分支时,如果可能,Git会用Fast forward模式,但这种模式下,删除分支后,会丢掉分支信息. 如果要强制禁用Fast forward模式,Git就会在merge时生成一个新的comm ...