r/Zenject•
1winter

ZenjectResolveException: Could not find required dependency with type when injecting into

First post on r/Zenject, woot! Let me start off by saying thanks for creating such a great tool, it's really helped me finally start to grasp DI and appreciate what it can bring to a project. I'm having an issue with a Factory. When I use it without any extra parameters, it works fine, but I'm trying to pass a set of attributes to a newly created object and it's throwing the error in the subject line. Here's my code snippets below:

Installer.cs:
---------------
using Zenject;
using UnityEngine;

public class Installer: MonoInstaller 
{
    public Settings SceneSettings;
    
    public override void InstallBindings()
    {
        Container.Bind<Settings>().ToSingleInstance(SceneSettings);
        Container.Bind<GridCreator>().ToSingle();
        Container.BindGameObjectFactory<Tile.Factory>( SceneSettings.Tile.Prefab );
    }
}

[Serializable]
public class Settings
{ ... }



Tile.cs:
---------------
using UnityEngine;
using Zenject;

public class Tile : MonoBehaviour
{
    [Inject] TileAttributes _attributes;

    [PostInject]
    public void Initialize()
    {
        transform.GetComponent<MeshRenderer>().sharedMaterial = _attributes.Material;
        transform.name = _attributes.Name;
    }

    public class Factory : GameObjectFactory<TileAttributes, Tile>
    {
    }
}



TileAttributes.cs:
-------------------
using UnityEngine;

public class TileAttributes
{
    public string Name;
    public Material Material;
}



GridCreator.cs:
--------------------
using UnityEngine;
using Zenject;

public class GridCreator: IInitializable
{
    private Settings _settings;
    private Tile.Factory _tileFactory;

    public GridCreator( Tile.Factory tileFactory, Settings settings )
    {
        _tileFactory = tileFactory;
        _settings = settings;
    }

    public void Initialize()
    {
        CreateGrid();
    }

    private void CreateGrid()
    {
        var sizeX = _settings.Grid.GridSizeX;
        var sizeY = _settings.Grid.GridSizeY;
        TileAttributes _tileToUse;
        var tileMaterials = _settings.Tile.TileMaterials;
        var tilesToChooseFrom = _settings.Tile.TilesToUse;

        for ( var x = -1; x <= sizeX; x++ )
        {
            for ( var z = -1; z <= sizeY; z++ )
            {
                if ( x == -1 || x == sizeX || z == -1 || z == sizeY )
                {
                    _tileToUse = _settings.Tile.TileMapBorder;
                }
                else
                {
                    _tileToUse = tilesToChooseFrom[Random.Range( 0, tilesToChooseFrom.Count )];
                }

                var addedTile = _tileFactory.Create( _tileToUse );
            }
        }
    }
}

The actual error thrown is "ZenjectResolveException: Could not find required dependency with type 'TileAttributes' when injecting into 'Tile' ".

I've tried changing it to a simple string and hard-coding what is passed in _tileFactory.Create() and i still get the same issue. If i remove the custom parameter, the factory creates objects perfectly--i just can't seem to figure out how to inject them properly.

I've debugged it and removed the custom parameter temporarily and ensured that _tileToUse is properly initialized/set when it's passed to _tileFactory.Create(), so I'm at a loss as to where I'm going wrong.

I'm still very new to DI, so if my code is blatantly offensive and wrong lol, please let me know--I'm looking to learn and ensure I'm following the pattern correctly before I continue to implement it the way I understand it. Any guidance is much appreciated. :)

Thanks!

Posted May 27, 2015, 1:40 PM UTC · edited

34
1winterOP•

ahh, adding

Container.Bind<TileAttributes>().ToSingle();

to my installer seems to have resolved it. Will still take any comments or suggestions! :)

1
leahayes•

Yeah you just needed to somehow define the binding.

Here are a few general suggestions:

  1. Try to use constructor injection wherever possible.

  2. Bind concrete types to abstract types (like interfaces, for instance) since this decouples implementations from their interfaces/contracts allowing you to substitute different implementations. This is great when unit testing/mocking, or when you want to provide platform-specific overrides:

     // InstallerExample
    
     #if ADVERTS_ADMOB
     Container.Bind<IAdvertPopupService>().ToSingle<AdMobAdvertPopupService>();
     #elif ADVERTS_CHARTBOOST
     Container.Bind<IAdvertPopupService>().ToSingle<ChartBoostAdvertPopupService>();
     #else
     Container.Bind<IAdvertPopupService>().ToSingle<NullAdvertPopupService>();
     #endif
    

Elsewhere you dont need to know WHICH advert service is in play (or indeed if any is in play), you just need to know how to use the interface.

I hope that this helps :)

1
brain_emesis•

It looks like you want to provide the TileAttributes argument dynamically from within GridCreator, so the line:

Container.Bind<TileAttributes>().ToSingle();

Shouldn't be necessary.

The code looks fine to me and seems like it should work. I just tried basically the same thing in a test project and it worked as expected. What version of Zenject are you using? What might help is to strip the problem down to the bare minimum and then create a test project that I could try.

I'll also echo what leahayes said about avoiding doing field injection whenever possible in favour of constructor injection or PostInject injection. I'd suggest changing your Tile class to this:

public class Tile : MonoBehaviour
{
    TileAttributes _attributes;

    [PostInject]
    public void Initialize(TileAttributes attributes)
    {
        _attributes = attributes;

        transform.GetComponent<MeshRenderer>().sharedMaterial = _attributes.Material;
        transform.name = _attributes.Name;
    }

    public class Factory : GameObjectFactory<TileAttributes, Tile>
    {
    }
}
1
1winterOP•

Sooo the issue is that this was a test project I've been learning Unity on for the last 2 weeks and cleaning up as I go, and I had some other components on the Tiles in question (or something), that even though they didn't reference TileAttributes, were somehow causing the error. I realized something was up when I made a Factory for a separate kind of object called Block, using the same exact code but with different variable names as my Tile Factory, and didn't have to include a reference to BlockAttributes in my Installer.

Once I cleaned up the project and removed all of the old, unused test code, I was able to remove the TileAttributes reference in the installer. I actually got further and made GridCreator an IFactory for my Tiles so that I can plug in a different (theoretically more complex) version at a later date.

I'd post some code, but I'm lazy. Basically, once I realized I could use Constructor injection with MonoBehaviours using the [PostInject] flag, all of my code became even cleaner and easier to read. It's a great feeling to finally understand DI and IoC--between this and learning delegates/events in the last week, I feel like I just had my Neo "I know Kung Fu moment" with C#. :D

2