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. Python 读写文件中数据

    1 需求 在文件 h264.txt 中的数据如图1,读入该文件中的数据,然后将第1列的地址删除,然后将数据输出到h264_out.txt中: 图1 h264.txt 数据截图             ...

  2. ThinkPHP中疑难笔记

    不但要记住核心的东西, 还要记住 相关的 东西: 如php cli的版本是 5.6.14 bulit: sep 30, 2015 tp中, 通常说的系统就是框架; 项目就是 "应用程序&qu ...

  3. CSS大杂烩(1)

    box-sizing 有4种方式 border-box 用来减去padding内边框和边框 前提是设置好固定宽高 content-box 在宽和高之外内边距和边框 其实基本上和原来一样 inherit ...

  4. Backbone源码阅读手记

    Backbone.js是前端的MVC框架,它通过提供模型Models.集合Collection.视图Veiew赋予了Web应用程序分层结构.从源码中可以知道,Backbone主要分了以下几个模块: ( ...

  5. 使用 JavaScript 实现简单候选项推荐功能(模糊搜索)【收藏】【转】

    当我们使用 Google 等搜索功能时,会出现与搜索内容有关的候选项.使用 JavaScript 搜索字符串,通常会使用 indexOf 或者 search 函数,但是非常僵硬,只能搜索匹配特定词语. ...

  6. Unity3D 之脚本架构,优雅地管理你的代码

    本文参考雨松MOMO大神的帖子: 图片全部来自他的帖子(请允许我偷懒下) --------------------------------------------------------------- ...

  7. Digital calculation

    No1=1 No2=2 1. let result=No1+No2   let No1++    let No1+=3 2. result=$[No1+No2] 3. result=$((No1+No ...

  8. 如何撤销 PhpStorm/Clion 等 JetBrains 产品的 “Mark as Plain Text” 操作 ?

    当把某个文件“Mark as Plain Text”时,该文件被当做普通文本,就不会有“代码自动完成提示”功能,如下图所示: 但是呢,右键菜单中貌似没有 相应的撤销 操作, 即使是把它删除,再新建一个 ...

  9. PHP计算一年有多少周,每周开始日期和结束日期

    一年有多个周,每周的开始日期和结束日期 参考代码一:[正在使用的版本] <?php header("Content-type:text/html;charset=utf-8" ...

  10. 一个asp采集程序

    <% if request.QueryString="" then url="http://www.hbcz.gov.cn:7001/XZQHQueryWAR/xx ...