Any dependency injection framework recommend?

Hi~ I’m searching a DI framwork.

I found Zenject, but it stoped update add support at 2020.

Would you recommend a good solution? Thanks!

There’s extenject, the continuation of zenject.

https://github.com/Mathijs-Bakker/Extenject

Thank you!

From a recent quick search I did, it seems Extenject is currently the best solution.

Thank you~ I’m looking at VContainer: https://github.com/hadashiA/VContainer

For anyone coming into this thread circa April 2023.

Extenject is no longer being actively maintained :frowning:
VContainer is being actively maintained.

I would still use Extenject as it has many features that VContainer does not!

Things you can do in Extenject that aren’t possible with VContainer (unless you’re willing to extend the framework yourself).

  • Bind Memory Pools
  • Bind multiple interfaces to different concrete type based on conditionals
  • [InjectOptional] attribute (useful if an object doesn’t always need a dependency)
  • Resolve dependencies from sub containers
  • Use the decorator pattern.

As well as this, Extenject offers multiple ways to accomplish the same task, where as VContainer barely provides the one solution.

Documentation is also much more scarce.

VContainer is better when comparing features it ACTUALLY has (which is 10% of Extenject).

Maybe if you really knew what you where doing and where happy to write a ton of DI boiler plate code you will find VContainer the better solution (again it can do everything Extenject can do, and in theory do it better, if you write the code yourself)

I think a core issue is both Extenject and VContainer try to maintain standalone DI framework, where as we really need a DI framework that’s user friendly and built specifically for Unity.

It’s so sad that Zenject/Extenject is not maintained anymore. Vcontainer lacks features and accessibilty that Zenject has. Not much hope on DI frameworks :frowning:

Did anyone try Reflex?

While Extenject/Zenject may not be maintained anymore it works fine in Unity 2022.3. I have been using it for almost a year now and have absolutely no issues.

I’m not really interested in standalone DI frameworks so I’m currently investigating these for avoiding singletons purposes:

Init(args): https://assetstore.unity.com/packages/tools/utilities/init-args-200530#description
Switchboard: https://assetstore.unity.com/packages/tools/utilities/switchboard-250879#description

Personally, for many years I always used AutoFac which is just a standard C#/.NET dependency injection and Inversion of Control library. I always thought it was the best. But it’s not a drop-in solution, you’d have to integrate it yourself. I personally avoid much of the “made for Unity3D” solutions because to me they seemed not as great compared to their popular standard .NET counterparts. Of course this 10 years ago when I was looking for a DI/IoC library to use in Unity3D so maybe things have changed and the Unity3D specific libraries are great now compared to AutoFac.

There is this: Dependency injection - .NET | Microsoft Learn

My (somewhat off topic) question would be: Do you need DI/interfaces and how do you gain over basic singleton use?
For example if you plan on replacing a complete module from time to time the the interface & DI or service locator makes sense, you can swap any time. If you have a special version of modules for testing - again makes sense.
But if you only ever end up using 1 game-manager class, 1 server communication class etc, I am not sure what the added dev overhead of not using a singleton directly (no interface) gains you. So do you need it?

If a dependency inject framework is so good why haven’t Unity bothered doing something about it?

You mean the company that struggles to make proper systems? Unity already has something in place that is a form of dependency injection: the Inspector. Why they haven’t gone beyond that is likely a case of they don’t see a need to do it themselves but then this is a company that took years to provide an official object pooling system.

Thanks for the shout out!

I am planning to submit version 1.1.0, hopefully today. I’ve been editing and re-writing the whole documentation, so it should be much easier to understand when it goes live. Thanks to the interest of a few I’ve been very motivated over the holiday season to work on polishing everything, and recording myself setting up a new demo project from scratch. I hope I can put out a video with a much better example project soon.

I would also recommend Init(Args) because @SisusCo is very active and responsive to users here.

Here are some of the other frameworks that I’ve seen:

Zenject
https://github.com/modesttree/Zenject

Extenject (Fork of Zenject)
https://github.com/Mathijs-Bakker/Extenject

UniDi (Fork of Zenject/Extenject
https://github.com/UniDi/UniDi

VContainer
https://vcontainer.hadashikick.jp/

StrangeIoC
https://strangeioc.github.io/strangeioc/

Reflex
https://github.com/gustavopsantos/Reflex

Frictionless
https://github.com/Claytonious/Frictionless

Binject
https://github.com/somedeveloper00/Binject

Injecter.Unity
https://kuraiandras.github.io/Injecter/documentation/injecter.unity.html

adic
https://github.com/intentor/adic

As a treat for forum regulars who promote static singletons and service locators over DI, I wanted to highlight something I learned recently about DI frameworks for Unity. Most of them don’t strictly do what they claim.

This section of Zenject’s documentation says: GitHub - modesttree/Zenject: Dependency Injection Framework for Unity3D
“If you want to instantiate a prefab at runtime and have any MonoBehaviour’s automatically injected, we recommend using a factory. You can also instantiate a prefab by directly using the DiContainer by calling any of the InstantiatePrefab methods. Using these ways as opposed to GameObject.Instantiate will ensure any fields that are marked with the [Inject] attribute are filled in properly, and all [Inject] methods within the prefab are called.”

Both of the links are broken, on both Zenject and Extenject docs, but if you look you can find this page about factories: Zenject/Documentation/Factories.md at master · modesttree/Zenject · GitHub

Their solution is to tightly couple your code to the Zenject PlaceholderFactory class, which negates the whole point of using dependency injection with the exact same criticism that they have of statics, tightly coupled dependencies. :smile:

They don’t even mention how you would inject a prefab dropped into a scene while playing. I’m assuming because it’s not supported. I’m of the opinion that if a DI framework can’t handle that use case, then it’s not actually a complete DI framework for Unity. From what I’ve seen most frameworks either don’t support it, or they say that if you really need that then they provide a handy dandy service locator, or some other tightly coupled framework dependency!

I appreciate the vote of confidence, thank you :slight_smile:

To be fair, I think the main criticisms brought up against the service locator pattern, like in the infamous Service Locator is an Anti-Pattern blog post by Mark Seemann, were never really so much about avoiding coupling with a particular framework, but more about the practical experience of using the API of the service locator as a programmer:

  • ServiceLocator.Get<T>() implies that it can provide an instance of any type on request, but in reality it can only return some subset. There’s no way to know which types it can return and which not, from just looking at the API. The compiler also won’t be able to help.
  • Similarly, if you want to create an instance of an object that uses a service locator for resolving its dependencies internally, the compiler won’t be able to tell you whether it is possible or not in a particular context. The code will compile, but it may or may not throw an exception at runtime time due to some service not being registered with the service locator.

One of the main benefits of dependency injection is that it can help make the dependencies of services explicit, and even go as far as making it practically impossible to create an instance of an object without providing it all its dependencies.

var service1 = new Service1();
var service2 = new Service2();
//var client = new Client(); // <- does not compile
var client = new Client(service1, service2); // <- compiles

Zenject does (kind of) avoid the issues described by Mark Seemann with its factories:

public class Enemy
{
    readonly Player _player;
    readonly float _speed;

    public Enemy(float speed, Player player)
    {
        _player = player;
        _speed = speed;
    }
}

public class EnemyFactory : PlaceholderFactory<float, Enemy> { }
  • When creating the Enemy class, you don’t need to spend time thinking how to resolve its dependencies, you simply declare them.
  • If you try to create an instance of Enemy in code, you won’t be able to do it without providing it with all its services - the compiler will make sure of it.

However, since Zenject is at the end of the day, all about using a DI container to resolve dependencies instead of pure DI, most of these benefits will not actually really apply very much in practice. You can still find yourself in situations where you don’t know if a component will or will not work when you hit Play Mode, as it can depend on what Context objects you’ve assigned to some components, and what code exists in various installers. In this sense, I think it is a step back from Unity’s serialized field based DI, where you can in many cases clearly see all the other objects that a component depends on listed in the Inspector, and as long as you drag-and-drop an instance to each slot, you will know that the instance has been provided with all the services it needs.

In Init(args) I’ve also tried to avoid the two downsides brought up by Mark Seemann, both on the code side, as well as the Inspector side.

On the code side, it is possible to use pure DI, and the compiler will be able to help ensure that all dependencies have been provided properly.

prefab.Instantiate(service1, service2);

gameObject.AddComponent<Client, Service1, Service2>(service1, service2);

Services can also be configured using the inspector, in which case missing services are highlighted in red, and the user is warned about them both in edit mode and at runtime, and provided with (hopefully) helpful error messages describing what went wrong and how to fix it.
9567415--1353574--Automatic Null Validation.jpg

Problem #2 is still a thing in Init(args), when the Inspector is used to configure services; the compiler will not be able to warn about trying to instantiate a prefab with missing services. However, since that validation is still taking place in edit mode, I think that the pain point is at least alleviated to a large extend.

I believe that is supported in Zenject using the ZenAutoInjecter component.
9567415--1353607--ZenAutoInjecter.png

Yeah, that’s a good point. However, I feel like that’s why nothing can beat constructor injection, and when we can’t use constructors then we’re just trying to recreate lost functionality. Most of the conventional wisdom comes from an environment where constructor injection is a legitimate alternative to ever using a service locator.

My take is that the service locator should only be accessed from one place, namely OnEnable(), and you can just set enabled = false if a required type is not provided. The component will disable, sort of like an object failing to initialize if a constructor throws an ArgumentNullException. Of course, that places the burden on the user to handle usage of the service locator as expected, but personally I have no problem with expecting users to know how to use something and not abuse it. Call it from OnEnable(), if a dependency is required set enabled = false, similar to System standard library constructors throwing an ArgumentNullException when a null is passed via constructor injection. With constructors the object is not created, with OnEnabled the component remains disabled, and other code can check the enabled status.

However, I understand your admirable efforts to provide users with guarantees about whether types will resolve. It’s true that my methodology provides no such guarantees. If there is nothing at the composition root, you just get null references. I leave it up users to just know that potential and code appropriately. If constructor injection were possible, I would also steer everyone clear of service locators.

Ah, good point! I was not exact enough with my wording the first time, an easy thing to do when discussing a complex topic. I should have said that they do not support it without adding a framework specific component to your game object. If Zenject were removed you would have to delete all of those components one by one, and then code a completely different DI solution into the dependent objects.

That’s not a good idea.

Ideally, when you try to do that, your project should fail to compile. When you are shifting checks to runtime, you’re losing safety mechanims provided by C# type safety system. A runtime error is the one that might not surface until the most inconvenient moment.

That’s fair, but the system is honestly only intended serve a very specific, single responsibility, and only due to the limitations of the Unity environment. That is to replace direct references to singletons and static classes.

Those exceptional failures should explode right away when you hit play, pretty much every single time. They are the types of dependencies that are not strangely referenced in some far reaches of the application.

If you were worried that it might happen, you could easily create a test to run with unit tests, or in the type of special scene that must be loaded first that many seem to need. However, it wouldn’t really be required for the app to start, just a unit test to make sure all necessary dependencies are always assigned in the currently assigned injector asset.

It is only meant to replace the handful of singletons that everyone currently uses, so they can be modular interface references instead. If it’s referenced anywhere else, other than initializing a MonoBehaviour in Awake, then it’s not really a supported use case.

Oh, and the way my service locator is referenced, it is only intended to be directly referenced on a single line, again in Awake(). The entire service locator is 30 lines of open source code with no other dependencies. And, from that point onward, everything else is handled via loosely coupled interface reference to the depedency injector asset that’s assigned in the editor.