DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Mastering Coroutine Execution: Yielding, Flow, and Practical Use Cases in Unity
  • Unity and the Future of Game Development
  • Automate Private Azure Databricks Unity Catalog Creation
  • Leveling Up Your Unity Coroutines: Advanced Patterns, Debugging, and Performance Optimization

Trending

  • The Smart Way to Talk to Your Database: Why Hybrid API + NL2SQL Wins
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • Infrastructure as Code (IaC) Beyond the Basics
  • How GitHub Copilot Helps You Write More Secure Code

Unity: Passing Constructor Parameters to Resolve

By 
Mikael Koskinen user avatar
Mikael Koskinen
·
May. 04, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
23.2K Views

Join the DZone community and get the full member experience.

Join For Free

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:

 
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));
}

Sample code

The above examples can be found from GitHub.

unity Game engine

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Coroutine Execution: Yielding, Flow, and Practical Use Cases in Unity
  • Unity and the Future of Game Development
  • Automate Private Azure Databricks Unity Catalog Creation
  • Leveling Up Your Unity Coroutines: Advanced Patterns, Debugging, and Performance Optimization

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!