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.