1

I already have created a object by Activator.CreateInstance(). How can I inject dependency that object having? As a reference, I use c# and zenject of Unity3d.

public abstract class Task
{
    [Inject(Id = "Json")]
    protected ISerializer Serializer;

    public abstract void Execute();

    public abstract void SetPacket(byte[] bytes);
}

public class LoginTask : Core.NetWork.Websocket.Task
{
    private LoginResp packet;
    
    public override void Execute()
    {
        Log.WriteConsole($"== ws login task execute={packet.permit}");
    }

    public override void SetPacket(byte[] bytes)
    {
        packet = serializer.Deserialize<LoginResp>(bytes);
    }
}

public Task GetTask(byte header)
{
    Log.WriteConsole($"== packet type={header}");
    PacketType packetType = _packetType.GetType().GetFields()
            .Select(field => (PacketType)field.GetValue(_packetType))
            .First(p => p.Header.Equals(header));
    return (Task) Activator.CreateInstance(packetType.Type);
}

I am supposed to use Activator.CreateInstance() of GetTask() for getting task. And then, I just want some serializer(which was registered in Container of zenject) to be injected into LoginTask created already.

Dennis
  • 130
  • 10
  • 1
    you mean like `Container.Bind(_foo.GetType().BaseType()).FromInstance(_foo)`? How does `Activator.CreateInstance()` relate to zenject? – Omar Abdel Bari Nov 08 '21 at 01:44
  • We have no existing code for which we can help. If you want to get relevant answers kindly provide a minimum reproducible set of code and a clear description of the problem. – Omar Abdel Bari Nov 08 '21 at 01:44
  • Thanks your comment. @Omar Abdel Bari. I did add my codes. – Dennis Nov 08 '21 at 02:15
  • Btw, you should use a different name for your class instead of `Task` - that’s a very commonly used type (`System.Threading.Tasks.Task`) so you’ll run into ambiguity errors. – Dai Nov 08 '21 at 02:17
  • 1
    You'll likely want to use the factory pattern in such a case. Zenject does have `IFactory` [which you can find here](https://github.com/modesttree/Zenject#binding) but I haven't used it myself. Worst case, you could just create one on your own. Whoever wants the `LoginTask` will request it from the factory. The factory will have a constructor which obtains the serializer. When requested, the factory will create the `LoginTask` and will have provide the serializer. – Omar Abdel Bari Nov 08 '21 at 03:23
  • Why does `LoginTask` not have a constructor that takes a serializer? Is this a gameobject or something else? If you did that couldn't you use an overload of `CreateInstance` that provides the parameter? – Omar Abdel Bari Nov 08 '21 at 03:25
  • Because serializer of Task use field injection. Anyway, I think that's good idea for using factory of zenject. thanks – Dennis Nov 08 '21 at 06:46

0 Answers0