Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it matter in which order to call RegisterType in Unity injection container in C#?

Let's assume, we have several classes like this:

public class WorkerLevel1 : IWorkerLevel1
{
  public WorkerLevel1(IDependency1 dep1, IWorkerLevel2 workerLevel2)
  {
    ...
  }
}

public class WorkerLevel2 : IWorkerLevel2
{
    public WorkerLevel2(IDependency2 dep2)
    {
      ...
    }
}

When we do registrations, does it matter in which order we call RegisterType method? (lines 1-4 below)

container.RegisterType<IDependency1,Dependency1>();
container.RegisterType<IDependency2, Dependency2>();
container.RegisterType<IWorkerLevel2, WorkerLevel2>();
container.RegisterType<IWorkerLevel1, WorkerLevel1>();
like image 606
Artemy Avatar asked Sep 16 '14 07:09

Artemy


People also ask

Which injection is applied when new object is instantiated through Unity container?

When creating an object, the container uses one of the following algorithms to select a constructor it will be using to initialize the object: Constructor Injection using explicit registration.

What is the use of Unity container in C#?

Unity container allows us to register an existing instance using the RegisterInstance() method. It will not create a new instance for the registered type and we will use the same instance every time. Thus, we can register and resolve different types using Unity container.

Is Unity IoC container?

Unity is an IoC container released by Microsoft and is very simple, flexible and easy to use. Though there are many IoC containers available in the market much stronger than Unity, for simplicity and to understand the basic concepts, it's one of the best choices.

What is container resolver Unity?

The Unity container identifies type registrations and type mappings in the container using a type and, optionally, a name. The type is an interface or a class (usually an interface or base class) that the desired concrete object type implements or inherits.


1 Answers

It doesn't matter, as long as the interfaces you're registrering are all different.

When registering the same interface multiple times however, the ordering does matter; in that case, each subsequent call to RegisterType will overwrite the previous registration for that interface.

like image 68
Leon Bouquiet Avatar answered Sep 21 '22 17:09

Leon Bouquiet