0

I have a legacy library that gets all the classes implementing IFoo<T>, instantiate them as singleon, and execute their Execute medhod.

I need to have a transient lifetime, and the implementation's constructor injected through DI and still make it compatible with the old system. But I cannot touch the legacy library.

So my idea is to create an interface ISuperFoo<T> with the same method that represents the transient lifetime, and at compile time generate IFoo<T> wrappers that instantiate a super-foo of T through our dependency injection framework in each execution, and that are picked up automatically by the legacy library.

I have been researching and it seems that it may be possible to do this through Roslyn, generating code at compile time like when state machines for async/await are created.

Found similar old questions, but wonder if now it is possible with https://www.nuget.org/packages/CodeGeneration.Roslyn.BuildTime.

Basically I have:

interface IFoo<T>
{
    void Execute(T obj);
}

And at compile time I want to generate something like:

[EditorBrowsable(false)]
class FooWrapper<T> : IFoo<T>
{
    Container _container;

    public FooWrapper(Container container)
        => _container = container;

    public void Execute(T obj)
        => _container
             .GetInstance<ISuperFoo<T>>()
             .Execute(obj);
}

Container can be injected because it will be a singleton anyway.

vtscop
  • 31
  • 11
  • BTW, `ServiceLocator` is not DI. You're not injecting anything. Yes, it's "kind of" an IoC, but actually it's an anti-pattern. To your question: you're probably looking for IL weaving like Fody or PostSharp. – dymanoid Sep 09 '19 at 13:56
  • Fair point. I just wanted to show a simplification of the problem. I will take a look at those thanks. – vtscop Sep 09 '19 at 14:00
  • Can't you use something like Harmony or Fody? https://github.com/pardeike/Harmony/wiki – Lucca Ferri Sep 09 '19 at 15:20

1 Answers1

0

With Source Generators (currently in preview) you should be able to do this.

See https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/

Yair Halberstadt
  • 5,733
  • 28
  • 60