Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Do you use dependency injection? Is it worth it?

Discussion in 'Scripting' started by michal_k, Nov 11, 2015.

  1. michal_k

    michal_k

    Joined:
    Jul 31, 2014
    Posts:
    33
    Hi,

    recently I've learned about dependency injection. In Android it is easy to use such library - for example in Dagger (http://google.github.io/dagger/) you use a set of Java annotations.

    I've searched the Asset Store and all plugins use weird syntax like:
    Code (CSharp):
    1.        injectionBinder.Bind<IExampleModel>().To<ExampleModel>().ToSingleton();
    while all I want to do is create singletons and use [Inject] annotations.

    Is is possible to have this in a simpler way? Do you use DI/is it worth it? Apart from cleaner code, AFAIK the main reason is to use it for tests, which I personally don't plan to use in Unity.

    Thanks.
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    You will be constantly fighting against Unity trying to implement a dependency injection function. Traditional dependency injection relies on using a constructor to set up all of the dependencies. You can't access the constructor of a MonoBehaviour. Hence all the weird syntax to get it to work in Unity.

    I've never personally tried using dependency injection at Unity. So I can't tell you if it will be worth it. But its a lot of boiler plate code to make it work.
     
    Nigey and michal_k like this.
  3. michal_k

    michal_k

    Joined:
    Jul 31, 2014
    Posts:
    33
    I see, thanks for answering.
    So I think I'll just stick with singletons with static accessors then...
     
  4. Nigey

    Nigey

    Joined:
    Sep 29, 2013
    Posts:
    1,129
    Yeah I did a long long long research into IoS Containers and DI in Unity. I found there's about 4 different Asset Store DI Framework's, but only a small(ish) number of people use them really. They're good in specific circumstances, but most of their users are trying to override the 'Unity Way'.

    The majority of the developers I've seen stick to the composite or singleton design pattern :).
     
    Last edited: Nov 12, 2015
    michal_k likes this.