Skip to content

Automatic source generated extensions #63

@PereViader

Description

@PereViader

ManualDI excels at being able to add reusable extension methods on the container.
However these extensions require the user to call them manually

For instance, given

public interface ITickable { 
      void Tick();
}

public interface ITickableService {
    void Register(ITickable tickable);
    void Unregister(ITickable tickable);
}

public static class TickableServiceManualDiExtensions
{
    public Binding<TApparent, TConcrete> LinkTickable<TApparent, TConcrete>(this Binding<TApparent, TConcrete> binding)
        where TConcrete : ITickable
    {
         return binding
              .Initialize((o,c) => c.Resolve<ITickableService>().Register((ITickable)o)
              .Dispose((o,c) => c.Resolve<ITickableService>().Unregister((ITickable)o));
    }
}

Notice that on bindings, this will require calling the LinkTickable method for each and every type

public SomeTickable : ITickable { ... }
public OtherTickable : ITickable { ... }

b.Bind<SomeTickable>().Default().FromConstructor().LinkTickable();
b.Bind<OtherTickable>().Default().FromConstructor().LinkTickable();

This feature proposes adding an attribute ManualDiGeneratorExtension that can be added to static extension methods so that the source generator could add the call to the extension method automatically whenever the TConcrete is a valid target.

Thus the previous code would then turn into

public static class TickableServiceManualDiExtensions
{
    [ManualDiGeneratorExtension]
    public Binding<TApparent, TConcrete>LinkTickable<TApparent, TConcrete>(this Binding<TApparent, TConcrete> binding)
        where TConcrete : ITickable
    {
         return binding
              .Initialize((o,c) => c.Resolve<ITickableService>().Register((ITickable)o)
              .Dispose((o,c) => c.Resolve<ITickableService>().Unregister((ITickable)o));
    }
}

and then the bindings could be implemented just with

b.Bind<SomeTickable>().Default().FromConstructor();
b.Bind<OtherTickable>().Default().FromConstructor();

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions